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", // name27 false, // durable28 false, // delete when unused29 false, // exclusive30 false, // no-wait31 nil, // arguments32 )33 failOnError(err, "Failed to declare a queue")34 35 body := "Hello World!"36 err = ch.Publish(37 "", // exchange38 q.Name, // routing key39 false, // mandatory40 false, // immediate41 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", // name27 false, // durable28 false, // delete when unused29 false, // exclusive30 false, // no-wait31 nil, // arguments32 )33 failOnError(err, "Failed to declare a queue")34 35 msgs, err := ch.Consume(36 q.Name, // queue37 "", // consumer38 true, // auto-ack39 false, // exclusive40 false, // no-local41 false, // no-wait42 nil, // args43 )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 <-forever56 }
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!