1.介紹
使用amqp的庫用golang語言進行rabbitmq的開發,此文章的代碼可以用來安裝完成rabbitmq後,進行測試。也可以作為學習rabbitmq的第一個測試程式。
2.golang rabbitmq庫地址
https://github.com/streadway/amqp
3.錯誤處理
func failOnErr(err error, msg string) { if err != nil { fmt.Println("msg", err, msg) panic("error") }}
4. 建立串連
func mqConnect() { var err error conn, err = amqp.Dial(mqurl) failOnErr(err, "connect") channel , err = conn.Channel() failOnErr(err, "channel")}
5.中斷連線
func close(){ channel.Close() conn.Close()}
6.聲明交換器、訊息佇列並發送訊息
func push() { if channel == nil { mqConnect() } mgsConnect := "hello world" err := channel.ExchangeDeclare(exchange, "direct", false, false, false,false, nil) failOnErr(err, "ExchangeDeclare") _, err = channel.QueueDeclare(queueName, false, false, false, false, nil) failOnErr(err, "QueueDeclare") err = channel.QueueBind(queueName, "info", exchange, false, nil) failOnErr(err, "QueueBind") err = channel.Publish(exchange, "info", false, false, amqp.Publishing{ ContentType:"text/plain", Body:[]byte(mgsConnect), }) failOnErr(err, "Publish") fmt.Println("push ok")}
.7消費訊息
func receive() { if channel == nil { mqConnect() } msg, ok, err := channel.Get(queueName, false) failOnErr(err, "") if !ok { fmt.Println("do not get msg") return } err = channel.Ack(msg.DeliveryTag, false) failOnErr(err, "") s := BytesToString(&(msg.Body)) fmt.Printf("receve msg is :%s\n", *s)}func BytesToString(b *[]byte) *string { s := bytes.NewBuffer(*b) r := s.String() return &r}
.8程式入口
package mainimport ( "github.com/streadway/amqp" "fmt" "bytes")var conn *amqp.Connectionvar channel *amqp.Channelconst ( queueName = "hello" exchange = "exchange1" mqurl = "amqp://username:password@localhost:5672/")func main() { push() receive() fmt.Println("end") close()}