Golang RABBITMQ Practice (two implementations of simple messaging)

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

1: Drive

Originally intended to write a driver, and later found that GitHub above already have, then I directly take off-the-shelf, drive using GITHUB.COM/STREADWAY/AMQP, Direct import can!

2:exchange and queue

In the previous article, we've created VirtualHost, Exchange and queue, so we'll define these constants first.

  

Const (    "push.msg.q"    Exchange  "t.msg.ex " = "amqp://shi:123@192.168.232.130:5672/test")      
var conn *amqp. Connection
var channel *AMQP. Channel

3: Error Handling

  

Func Failonerr (Err error, msg string) {if err! = Nil {log. Fatalf ("%s:%s", MSG, err) panic (FMT. Sprintf ("%s:%s", MSG, err)}}

4: Connect MQ

func mqconnect () {    var  err error    = amqp. Dial (mqurl)    "failed to connect TP RABBITMQ")    = Conn. Channel ()    "failed to open a channel")}

5:push

First on the code:

 func push () { if  channel == nil {mqconnect ()} msgcontent:  =  hello world!   "  channel. Publish (Exchange, QueueName,  false ,  , AMQP. publishing{ContentType:   text/plain
       " , Body: []  byte   

In fact, it is very simple to call the Channel function publish method, incoming Exchange name and queue name, the last parameter is the message content, contenttype we set to Text/plain, for the text type, Body is the message content, to pass in a byte array, so that a message is completed push, then we look at receive

6:receive

Code:

func receive () {ifChannel = =Nil {mqconnect ()} msgs, err:= Channel. Consume (QueueName,"",true,false,false,false, nil) failonerr (err,"") Forever:= Make (chanBOOL) go func () {//FMT. Println (*MSGS)         forD: =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}

by calling the channel. The consume function returns a Chan-type pipe that accepts a message, and then range this Chan, the received data is []byte, converted to string output

<-Forever This is to control the current thread does not exit

7: Entrance Main

  

Func Main () {    go func () {        for  {            push () time            . Sleep (1 * Time . Second)        }    } ()    receive ()    FMT. Println ("end")    close ()}

The For loop guarantees that a message is sent to MQ every second, and this place is guaranteed not to block the main thread with a co-process. The receive function cannot use a co-process, or the main thread exits. The close function frees the connection object, but in this case it is not effective because the thread will never quit automatically, only to think that CTRL + C or the program is dead, and the system restarts

8: Execution:

Switch to go file directory execution

Go Run main.go
//Run log 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: All code

Package Mainimport ("FMT"    "Log"    "bytes"    " Time"    "GITHUB.COM/STREADWAY/AMQP")varConn *AMQP. ConnectionvarChannel *AMQP. ChannelvarCount =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, MSGstring) {    ifErr! =Nil {log. Fatalf ("%s:%s", MSG, err) panic (FMT. Sprintf ("%s:%s", MSG, err)) }}func Mqconnect () {varERR 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 ()}//Connecting RABBITMQ serverfunc push () {ifChannel = =Nil {mqconnect ()} msgcontent:="Hello world!"Channel. Publish (Exchange, QueueName,false,false, AMQP. publishing{ContentType:"Text/plain", Body: []byte(Msgcontent),})} Func receive () {ifChannel = =Nil {mqconnect ()} msgs, err:= Channel. Consume (QueueName,"",true,false,false,false, nil) failonerr (err,"") Forever:= Make (chanBOOL) go func () {//FMT. Println (*MSGS)         forD: =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}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.