安装RabbitMQ
RabbitMQ中文相关文档:http://rabbitmq.mr-ping.com/
docker安装参考:https://www.jianshu.com/p/0a0d2315805a
# 拉取rabbitmq镜像,management是rabbitmq的web管理界面。不使用标签拉取是不带管理界面的
docker pull rabbitmq:management
# 启动rabbitmq容器,15672是web管理界面端口5672是rabbitmq端口
docker run --name rabbitmq -d -p 15672:15672 -p 5672:5672 rabbitmq:management
启动容器后,浏览器中访问http://127.0.0.1:15672来查看控制台信息
RabbitMQ默认的用户名:guest,密码:guest
RabbitMQ官方示例:https://www.rabbitmq.com/tutorials/tutorial-one-go.html
go代码
package rabbitmq
// 引入amqo包
import (
"fmt"
"github.com/streadway/amqp"
"log"
)
const (
LOGIN string = "guest"
PASSWORD string = "guest"
HOST string = "127.0.0.1"
PORT string = "5672"
VIRTUALHOST string = "/"
)
func Pushlish() {
// 创建链接
url := fmt.Sprintf("amqp://%s:%s@%s:%s%s", LOGIN, PASSWORD, HOST, PORT, VIRTUALHOST)
conn, err := amqp.Dial(url)
failOnError(err, "Failed to connect to RabbitMQ")
defer conn.Close()
// 打开一个通道
ch, err := conn.Channel()
failOnError(err, "Failed to open a channel")
defer ch.Close()
// 生成一个交换机(交换机不存在的情况下)
err = ch.ExchangeDeclare("excange_golang","direct", true,false,false, false, nil)
failOnError(err, "Failed to declare an exchange")
// 生成一个队列队列(队列不存在的情况下)
_, err = ch.QueueDeclare("queue_golang", true, false, false, false, nil)
failOnError(err, "Failed to declare an queue")
// 列队与交换机绑定
err = ch.QueueBind("queue_golang", "golang_routing_key", "excange_golang", false, nil)
failOnError(err, "Bind queue to exchange failure")
// 指定交换机发布消息
err = ch.Publish("excange_golang", "golang_routing_key", false, false,
amqp.Publishing{
ContentType: "text/plain",
Body: []byte("hello golang rabbit"),
})
failOnError(err, "Message publish failure")
}
func Get() {
// 创建链接
url := fmt.Sprintf("amqp://%s:%s@%s:%s%s", LOGIN, PASSWORD, HOST, PORT, VIRTUALHOST)
conn, err := amqp.Dial(url)
failOnError(err, "Failed to connect to RabbitMQ")
defer conn.Close()
// 打开一个通道
ch, err := conn.Channel()
failOnError(err, "Failed to open a channel")
defer ch.Close()
// 指定队列获取消息
msg, ok, err := ch.Get("queue_golang", true)
failOnError(err, "Message empty")
fmt.Println(string(msg.Body), ok)
}
func failOnError(err error, msg string) {
if err != nil {
log.Fatalf("%s: %s", msg, err)
}
}
测试
func main() {
// rabbitmq
rabbitmq.Pushlish()
// rabbitmq.Get()
}
查看控制台
image.png
image.png
网友评论