1.docke 中安装 rabbitmq
docker pull rabbitmq
2.运行 rabbitmq
docker run -d --name rabbitmq -p 5671:5671 -p 5672:5672 -p 4369:4369 -p 25672:25672 -p 15671:15671 -p 15672:15672 rabbitmq:latest
3.下载 rabbitmq golang 客户端
go get github.com/streadway/amqp
4.send.go
1 package main 2 3 import ( 4 "log" 5 6 "github.com/streadway/amqp" 7 ) 8 9 func failOnError(err error, msg string) { 10 if err != nil { 11 log.Fatalf("%s: %s", msg, err) 12 } 13 } 14 15 // 只能在安装 rabbitmq 的服务器上操作 16 func main() { 17 conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/") 18 failOnError(err, "Failed to connect to RabbitMQ") 19 defer conn.Close() 20 21 ch, err := conn.Channel() 22 failOnError(err, "Failed to open a channel") 23 defer ch.Close() 24 25 q, err := ch.QueueDeclare( 26 "hello", // name 27 false, // durable 28 false, // delete when unused 29 false, // exclusive 30 false, // no-wait 31 nil, // arguments 32 ) 33 failOnError(err, "Failed to declare a queue") 34 35 body := "Hello World!" 36 err = ch.Publish( 37 "", // exchange 38 q.Name, // routing key 39 false, // mandatory 40 false, // immediate 41 amqp.Publishing{ 42 ContentType: "text/plain", 43 Body: []byte(body), 44 }) 45 log.Printf(" [x] Sent %s", body) 46 failOnError(err, "Failed to publish a message") 47 }
5.recv.go
1 package main 2 3 import ( 4 "log" 5 6 "github.com/streadway/amqp" 7 ) 8 9 func failOnError(err error, msg string) { 10 if err != nil { 11 log.Fatalf("%s: %s", msg, err) 12 } 13 } 14 15 // 只能在安装 rabbitmq 的服务器上操作 16 func main() { 17 conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/") 18 failOnError(err, "Failed to connect to RabbitMQ") 19 defer conn.Close() 20 21 ch, err := conn.Channel() 22 failOnError(err, "Failed to open a channel") 23 defer ch.Close() 24 25 q, err := ch.QueueDeclare( 26 "hello", // name 27 false, // durable 28 false, // delete when unused 29 false, // exclusive 30 false, // no-wait 31 nil, // arguments 32 ) 33 failOnError(err, "Failed to declare a queue") 34 35 msgs, err := ch.Consume( 36 q.Name, // queue 37 "", // consumer 38 true, // auto-ack 39 false, // exclusive 40 false, // no-local 41 false, // no-wait 42 nil, // args 43 ) 44 failOnError(err, "Failed to register a consumer") 45 46 forever := make(chan bool) 47 48 go func() { 49 for d := range msgs { 50 log.Printf("Received a message: %s", d.Body) 51 } 52 }() 53 54 log.Printf(" [*] Waiting for messages. To exit press CTRL+C") 55 <-forever 56 }
6.分别在在两个窗口执行
go run ./send.go
2018/08/22 15:48:13 [x] Sent Hello World!
go run ./recv.go
2018/08/22 15:48:16 [*] Waiting for messages. To exit press CTRL+C
2018/08/22 15:48:16 Received a message: Hello World!