I have multiple objects of key-value type which i need to send to RabbitMQ and hence forward would consume them. So, after going through this RabbitMQ link. It only tells the way to publish a simple plain text message. Can anyone tell me how to publish and consume map objects in RabbitMQ go lang?
m := make(map[string]string)
m["col1"] = "004999010640000"
m["col2"] = "awadwaw"
m["col3"] = "13"
err = ch.Publish(
"EventCaptureData-Exchange", // exchange
q.Name + "Key", // routing key
true, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "?????",
Body: ????,
})
You need to serialize your Go object to eg. base64 text before publishing it. In your consumer, you then deserialize it to get back your initial object. See "Golang serialize and deserialize back" for an example in Go.
For the content type, I'm not sure what is the most appropriate. application/octet-stream
?
It's so simple. You can use json and bytes packages to serialize and deserialize messages. Prepared this example for you:
type Message map[string]interface{}
func serialize(msg Message) ([]byte, error) {
var b bytes.Buffer
encoder := json.NewEncoder(&b)
err := encoder.Encode(msg)
return b.Bytes(), err
}
func deserialize(b []byte) (Message, error) {
var msg Message
buf := bytes.NewBuffer(b)
decoder := json.NewDecoder(buf)
err := decoder.Decode(&msg)
return msg, err
}
Yeah, basically that's it. Body field in RabbitMQ library is byte array, therefore all you need are just converting to/from your data structure to/from byte array.