golang rabbitmq實踐 (二 實現簡單的訊息收發)

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

1:驅動

  本來打算自己寫一個驅動的,後來發現github上面已經有了,那我就直接拿現成的了, 驅動採用 github.com/streadway/amqp ,直接import就可以啦!

 2:exchange and queue

  在上一篇文章中,我們已經建立好virtualhost 、exchange and queue,所以我們先定義這些常量

  

const (    queueName = "push.msg.q"    exchange  = "t.msg.ex"    mqurl ="amqp://shi:123@192.168.232.130:5672/test")
var conn *amqp.Connection
var channel *amqp.Channel

 

3:錯誤處理

  

func failOnErr(err error, msg string) {if err != nil {log.Fatalf("%s:%s", msg, err)panic(fmt.Sprintf("%s:%s", msg, err))}}

4:串連mq

func mqConnect() {    var err error    conn, err = amqp.Dial(mqurl)    failOnErr(err, "failed to connect tp rabbitmq")    channel, err = conn.Channel()    failOnErr(err, "failed to open a channel")}

 

5:push

  先上代碼:

func push() {    if channel == nil {        mqConnect()    }    msgContent := "hello world!"    channel.Publish(exchange, queueName, false, false, amqp.Publishing{        ContentType: "text/plain",        Body:        []byte(msgContent),    })}

  其實是很簡單的,調用 channel函數的Publish方法,傳入exchange name 和 queue name,最後一個參數是訊息內容,ContentType我們設定為text/plain, 為文本類型,body是訊息內容,要傳入位元組數組,這樣就完成了一條訊息的push,接下來我們再看receive

6:receive

 代碼:

func receive() {    if channel == nil {        mqConnect()    }    msgs, err := channel.Consume(queueName, "", true, false, false, false, nil)    failOnErr(err, "")    forever := make(chan bool)    go func() {        //fmt.Println(*msgs)        for d := range msgs {            s := BytesToString(&(d.Body))            count++            fmt.Printf("receve msg is :%s -- %d\n", *s, count)        }    }()    fmt.Printf(" [*] Waiting for messages. To exit press CTRL+C\n")    <-forever}

  通過調用channel.Consume函數返回一個接受訊息的chan類型管道,然後range 這個chan,接收到的資料是[]byte,轉換為string後輸出

  <-forever  這個是為了控制當前線程不退出

7:入口main

  

func main() {    go func() {        for {            push()            time.Sleep(1 * time.Second)        }    }()    receive()    fmt.Println("end")    close()}

  for 迴圈保證每秒發送一條訊息到mq,這個地方採用協程保證不阻塞主線程。receive函數不能採用協程,不然主線程就退出了。close函數是釋放連線物件,但是在這個例子中是沒有起效的,因為線程永遠都不會自動結束,只能認為的CTRL+C 或者程式死掉,系統重啟

 

8:執行:

切換到go檔案目錄執行

go run main.go
//作業記錄receve msg is :hello world! -- 1246
receve msg is :hello world! -- 1247
receve msg is :hello world! -- 1248
receve msg is :hello world! -- 1249
receve msg is :hello world! -- 1250
receve msg is :hello world! -- 1251
receve msg is :hello world! -- 1252
receve msg is :hello world! -- 1253
receve msg is :hello world! -- 1254
receve msg is :hello world! -- 1255
receve msg is :hello world! -- 1256
receve msg is :hello world! -- 1257
receve msg is :hello world! -- 1258
receve msg is :hello world! -- 1259
receve msg is :hello world! -- 1260
receve msg is :hello world! -- 1261
receve msg is :hello world! -- 1262
receve msg is :hello world! -- 1263
receve msg is :hello world! -- 1264
receve msg is :hello world! -- 1265
receve msg is :hello world! -- 1266

9:全部代碼

package mainimport (    "fmt"    "log"    "bytes"    "time"    "github.com/streadway/amqp")var conn *amqp.Connectionvar channel *amqp.Channelvar count = 0const (    queueName = "push.msg.q"    exchange  = "t.msg.ex"    mqurl ="amqp://shi:123@192.168.232.130:5672/test")func main() {    go func() {        for {            push()            time.Sleep(1 * time.Second)        }    }()    receive()    fmt.Println("end")    close()}func failOnErr(err error, msg string) {    if err != nil {        log.Fatalf("%s:%s", msg, err)        panic(fmt.Sprintf("%s:%s", msg, err))    }}func mqConnect() {    var err error    conn, err = amqp.Dial(mqurl)    failOnErr(err, "failed to connect tp rabbitmq")    channel, err = conn.Channel()    failOnErr(err, "failed to open a channel")}func close() {    channel.Close()    conn.Close()}//串連rabbitmq serverfunc push() {    if channel == nil {        mqConnect()    }    msgContent := "hello world!"    channel.Publish(exchange, queueName, false, false, amqp.Publishing{        ContentType: "text/plain",        Body:        []byte(msgContent),    })}func receive() {    if channel == nil {        mqConnect()    }    msgs, err := channel.Consume(queueName, "", true, false, false, false, nil)    failOnErr(err, "")    forever := make(chan bool)    go func() {        //fmt.Println(*msgs)        for d := range msgs {            s := BytesToString(&(d.Body))            count++            fmt.Printf("receve msg is :%s -- %d\n", *s, count)        }    }()    fmt.Printf(" [*] Waiting for messages. To exit press CTRL+C\n")    <-forever}func BytesToString(b *[]byte) *string {    s := bytes.NewBuffer(*b)    r := s.String()    return &r}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.