golang寫第一個rabbitmq程式

來源:互聯網
上載者:User

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()}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.