Step By Step
1、RabbitMq控制台创建实例以及用户名&密码&Vhost
2、SDK 安装
gogetgithub.com/streadway/amqp
3、Send.go
packagemainimport ( "bytes""fmt""log""github.com/streadway/amqp") funcfailOnError(errerror, msgstring) { iferr!=nil { log.Fatalf("%s: %s", msg, err) } } funcmain() { varbufbytes.BufferuserName :="<username>"password :="<password>"buf.WriteString("amqp://") buf.WriteString(userName) buf.WriteString(":") buf.WriteString(password) // <Your End Point> 请从控制台获取。如果你使用的是杭州Region,那么Endpoint会形如 137000000010111.mq-amqp.cn-hangzhou-a.aliyuncs.combuf.WriteString("@<endpoint>:5672/<vhost>") url :=buf.String() fmt.Println(url) conn, err :=amqp.Dial(url) failOnError(err, "Failed to connect to RabbitMQ") deferconn.Close() ch, err :=conn.Channel() failOnError(err, "Failed to open a channel") deferch.Close() q, err :=ch.QueueDeclare( "helloqueue", // namefalse, // durablefalse, // delete when unusedfalse, // exclusivefalse, // no-waitnil, // arguments ) failOnError(err, "Failed to declare a queue") body :="Hello World!"err=ch.Publish( "", // exchangeq.Name, // routing keyfalse, // mandatoryfalse, // immediateamqp.Publishing{ ContentType: "text/plain", Body: []byte(body), }) failOnError(err, "Failed to publish a message") log.Printf(" [x] Sent %s", body) }
4、Receive.go
packagemainimport ( "bytes""fmt""log""github.com/streadway/amqp") funcfailOnError(errerror, msgstring) { iferr!=nil { log.Fatalf("%s: %s", msg, err) } } funcmain() { varbufbytes.BufferuserName :="<username>"password :="<password>"buf.WriteString("amqp://") buf.WriteString(userName) buf.WriteString(":") buf.WriteString(password) // <Your End Point> 请从控制台获取。如果你使用的是杭州Region,那么Endpoint会形如 137000000010111.mq-amqp.cn-hangzhou-a.aliyuncs.combuf.WriteString("@<endpoint>:5672/<vhost>") url :=buf.String() fmt.Println(url) conn, err :=amqp.Dial(url) failOnError(err, "Failed to connect to RabbitMQ") deferconn.Close() ch, err :=conn.Channel() failOnError(err, "Failed to open a channel") deferch.Close() q, err :=ch.QueueDeclare( "helloqueue", // namefalse, // durablefalse, // delete when unusedfalse, // exclusivefalse, // no-waitnil, // arguments ) failOnError(err, "Failed to declare a queue") msgs, err :=ch.Consume( q.Name, // queue"democs", // consumertrue, // auto-ackfalse, // exclusivefalse, // no-localfalse, // no-waitnil, // args ) failOnError(err, "Failed to register a consumer") forever :=make(chanbool) gofunc() { ford :=rangemsgs { log.Printf("Received a message: %s", d.Body) } }() log.Printf(" [*] Waiting for messages. To exit press CTRL+C") <-forever}
5、The Result
6、控制台监控查看