docker快速安装mq
docker run -d --hostname my-rabbit --name some-rabbit -e RABBITMQ_DEFAULT_USER=admins -e RABBITMQ_DEFAULT_PASS=123qwe123 -p15672:15672 -p5672:5672 rabbitmq:management-alpine
go 需要安装
go get github.com/streadway/amqp
生产者代码send.go
package main import ( "log" amqp "github.com/rabbitmq/amqp091-go" ) func failonError(err error, msg string) { if err != nil { log.Panicf("%s: %s", msg, err) } } func main() { conn, err := amqp.Dial("amqp://admins:123qwe123@192.168.64.6:5672/") 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( "test", // name false, // durable false, // delete when unused false, // exclusive false, // no-wait nil, // arguments ) failonError(err, "Failed to declare a queue") body := "bv xxxjbjb" err = ch.Publish( "", // exchange q.Name, // routing key false, // mandatory false, // immediate amqp.Publishing{ ContentType: "text/plain", Body: []byte(body), }) failonError(err, "Failed to publish a message") log.Printf(" [x] Sent %sn", body) }
消费者 receive.go
package main import ( "log" amqp "github.com/rabbitmq/amqp091-go" ) func failonError(err error, msg string) { if err != nil { log.Panicf("%s: %s", msg, err) } } func main() { conn, err := amqp.Dial("amqp://admins:123qwe123@192.168.64.6:5672/") 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( "test", // name false, // durable false, // delete when unused false, // exclusive false, // no-wait nil, // arguments ) failonError(err, "Failed to declare a queue") msgs, err := ch.Consume( q.Name, // queue "", // consumer true, // auto-ack false, // exclusive false, // no-local false, // no-wait nil, // args ) failonError(err, "Failed to register a consumer") forever := make(chan bool) go func() { for d := range msgs { log.Printf("Received a message: %s", d.Body) } }() log.Printf(" [*] Waiting for messages. To exit press CTRL+C") <-forever }
官网链接
https://www.rabbitmq.com/tutorials/tutorial-one-go.html
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)