1.基础环境依赖
下载并安装Eralng OTP For Windows(erlang的环境)
下载MQ Go的依赖
2.配置RabbitMQ
定位到rabbitmq的安装路径(图1-1):
接着输入rabbitmqctl status,出现类似如下说明安装成功(图2-2)
安装 RabbitMQWeb的管理插件,接着上面继续输入以下命令(rabbitmq-plugins enable rabbitmq_management)
之后可以通过http://127.0.0.1:15672/,为了安全起见,我们需要重新设置账户密码,首先输入rabbitmqctl.bat list_users来查询用户列表(图2-3),默认为guest:guest,新增用户输入rabbitmqctl.bat add_user username password,授予管理员权限输入rabbitmqctl.bat set_user_tags username administrator,rabbitmqctl.bat set_permissions -p / username "." "." ".*"),之后可用新的username和password登录账户了。
send.go
packagemain
import(
"log"
"github.com/streadway/amqp"
)
funcfailOnError(errerror,msgstring) {
iferr !=nil{
log.Fatalf("%s:%s", msg, err)
}
}
func main() {
conn,err:=amqp.Dial("amqp://guest:guest@localhost:5672/")
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(
"hello",//name
false,//durable
false,//delete when unused
false,//exclusive
false,//no-wait
nil,//arguments
)
failOnError(err,"Failed to declare a queue")
body:="hello"
err = ch.Publish(
"",//exchange
q.Name,//routing key
false,//mandatory
false,//immediate
amqp.Publishing{
ContentType:"text/plain",
Body: []byte(body),
})
log.Printf("[x] Sent%s", body)
failOnError(err,"Failed to publish a message")
}
receive.go
package main
import(
"log"
"github.com/streadway/amqp"
)
func failOnError(errerror,msgstring) {
iferr !=nil{
log.Fatalf("%s:%s", msg, err)
}
}
func main() {
conn,err:=amqp.Dial("amqp://guest:guest@localhost:5672/")
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(
"hello",//name
false,//durable
false,//delete when unused
false,//exclusive
false,//no-wait
nil,//arguments
)
failOnError(err,"Failed to declare a queue")
msgs,err:=ch.Consume(
q.Name,//queue
"",//consumer
true,//auto-ack
false,//exclusive
false,//no-local
false,//no-wait
nil,//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
}
测试结果