Golang RabbitMQ 推送 JSON 数据指南
可以使用 RabbitMQ 的 Go 客户端库 'github.com/streadway/amqp' 来推送 JSON 数据。
首先需要连接 RabbitMQ 服务器:
conn, err := amqp.Dial('amqp://guest:guest@localhost:5672/')
if err != nil {
// handle error
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
// handle error
}
defer ch.Close()
q, err := ch.QueueDeclare(
'myqueue', // queue name
false, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
if err != nil {
// handle error
}
然后可以将 JSON 数据转换为字符串,使用 Publish() 方法推送到队列中:
msg := map[string]interface{} {
'name': 'John',
'age': 30,
}
body, err := json.Marshal(msg)
if err != nil {
// handle error
}
err = ch.Publish(
'', // exchange name
q.Name, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: 'application/json',
Body: body,
},
)
if err != nil {
// handle error
}
以上代码将一个包含 'name' 和 'age' 字段的 JSON 对象推送到名为 'myqueue' 的队列中。ContentType 属性指定消息体的类型为 JSON。
原文地址: https://www.cveoy.top/t/topic/lAgV 著作权归作者所有。请勿转载和采集!