Golang|Golang rabbitMQ生产者消费者实现示例
目录
- 消费者
- 生产者
消费者
package mainimport ( "fmt" "github.com/streadway/amqp")func failOnError(err error, msg string) { if err != nil {fmt.Println("%s: %s", msg, err) }}// 只能在安装 rabbitmq 的服务器上操作func main() { conn, err := amqp.Dial("amqp://mquser:123456@127.0.0.1/toutiao") failOnError(err, "Failed to connect to RabbitMQ") defer conn.Close() ch, err := conn.Channel() failOnError(err, "Failed to open a channel") defer ch.Close() q, err := ch.QueueDeclare("toutiao.web.test", // 队列名字false,// durablefalse,// delete when unusedfalse,// exclusivefalse,// no-waitnil,// arguments ) failOnError(err, "Failed to declare a queue") msgs, err := ch.Consume(q.Name,// queue"toutiao",// consumertrue,// auto-ack,true消费了就消失false,// exclusivefalse,// no-localfalse,// no-waitnil,// args ) failOnError(err, "Failed to register a consumer") forever := make(chan bool) go func() {for d := range msgs {fmt.Println(fmt.Sprintf("返回的消息:%s",d.Body))} }() fmt.Println("[*] Waiting for messages. To exit press CTRL+C") <-forever}
生产者 body:消息体
package mainimport ( "github.com/streadway/amqp" "log")func failOnError(err error, msg string) { if err != nil {log.Fatalf("%s: %s", msg, err) }}// 只能在安装 rabbitmq 的服务器上操作func main() { conn, err := amqp.Dial("amqp://mquser:123456@127.0.0.1/toutiao") failOnError(err, "Failed to connect to RabbitMQ") defer conn.Close() ch, err := conn.Channel() failOnError(err, "Failed to open a channel") defer ch.Close() q, err := ch.QueueDeclare( "toutiao.web.test",// namefalse, // durablefalse, // delete when unusedfalse, // exclusivefalse, // no-waitnil, // arguments) failOnError(err, "Failed to declare a queue") body := "Hello World!"//发送的消息 err = ch.Publish( "",// exchangeq.Name, // routing keyfalse,// mandatoryfalse,// immediateamqp.Publishing{ContentType: "text/plain",Body:[]byte(body),}) log.Printf(" [x] Sent %s", body) failOnError(err, "Failed to publish a message")}
【Golang|Golang rabbitMQ生产者消费者实现示例】以上就是Golang rabbitMQ生产者消费者实现示例解析的详细内容,更多关于Golang rabbitMQ生产者消费者的资料请关注脚本之家其它相关文章!
推荐阅读
- Golang项目搭配nginx部署反向代理负载均衡讲解
- Golang语言JSON解码函数Unmarshal的使用
- golang组件swagger生成接口文档实践示例
- golang默认Logger日志库在项目中使用Zap日志库
- apache kafka和rabbitmq的区别
- kafka创建twitter生产者(producer)
- kafka生产者回调(callback)
- 在java中创建kafka生产者(producer)
- apache kafka生产者(producer)
- web项目中golang性能监控解析