英文:
How to publish and consume make(map[string]string) in rabbitmq go lang
问题
我有多个键值对类型的对象,我需要将它们发送到RabbitMQ,因此转发将消耗它们。所以,在阅读了这个RabbitMQ链接之后,它只告诉了如何发布一个简单的纯文本消息。有人可以告诉我如何在RabbitMQ的Go语言中发布和消费映射对象吗?
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: ????, // 消息体
})
英文:
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: ????,
})
答案1
得分: 6
这是一个简单的例子。你可以使用 json 和 bytes 包来序列化和反序列化消息。我为你准备了以下示例代码:
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
}
是的,基本上就是这样。在 RabbitMQ 库中,消息体是字节数组,因此你只需要将数据结构转换为字节数组,或者将字节数组转换为数据结构即可。
英文:
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.
答案2
得分: 3
你需要将你的Go对象序列化为例如base64文本,然后再发布它。在你的消费者端,你需要反序列化它以获取回你的初始对象。可以参考这个链接"https://stackoverflow.com/questions/28020070/golang-serialize-and-deserialize-back"中的Go示例。
至于内容类型,我不确定最合适的是什么。application/octet-stream
可以吗?
英文:
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 "https://stackoverflow.com/questions/28020070/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
?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论