RabbitMQ的简单使用
名词解释
P: producer 消息的产生者
Queue: 存储消息的缓冲区
C: consumer 消息的消费者
Exchange: 介于P和Queue之间,处理P发送的消息转发到queue
queue 模式
P将消息发送到指定queue, 订阅该queue的C,从中获取消息内容。多个C的模式,一般采用round-robin的方式获取queue里面的消息。
公共部分
// 创建一个mq的连接
conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
// 创建一个管道,channel
ch, err := conn.Channel()
// 给channel 申明指定的queue
q, err := ch.QueueDeclare(
"hello", // name
false, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
message publish
err = ch.Publish(
"", // exchange
q.Name, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "text/plain",
Body: []byte(body),
})
message consume
msgs, err := ch.Consume(
q.Name,
"",
false,
false,
false,
false,
nil,
)
failOnError(err, "Failed to register a consumer")
for d := range msgs {
log.Printf("Received a message: %s", d.Body)
}
publish/subscribe 模式
Instead, the producer can only send messages to an exchange. An exchange is a very simple thing.On one side it receives messages from producers and the other side it pushes them to queues. The exchange must know exactly what to do with a message it receives. Should it be appended to a particular queue? Should it be appended to many queues? Or should it get discarded. The rules for that are defined by the exchange type.
Exchange 作为producer 和 queue 之前的代理,有一定规则,决定将消息投递到哪个queue 或者丢弃消息. 几种类型 direct
, topic
, headers
and fanout
publish端
err = ch.ExchangeDeclare("logs", "fanout", true, false, false, false, nil)
failOnError(err, "Failed to declare a exchange")
body := "Hello World!" + time.Now().Format("2006-01-02 15:04:05")
err = ch.Publish("logs", "", false, false,
amqp.Publishing{
ContentType: "text/plain",
Body: []byte(body),
})
failOnError(err, "Failed to publish a message")
consumer 端
err = ch.QueueBind(q.Name, "", "logs", false, nil)
msgs, err := ch.Consume(q.Name, "", false, false, false, false, nil)
failOnError(err, "Failed to register a consumer")
for d := range msgs {
log.Printf(fmt.Sprintf("%d,", idx)+",Received a message: %s", d.Body)
}
routing 模式
如图所示,X: exchange type 选择direct,(finout 类型忽略routingkey), Q1 和X的 routingKey 是orange, Q2 和X的routingKey 是 black, green。P发送orange的消息会丢到Q1队列,发送black 或者 green 会丢到Q2队列里面,其他routingKey会丢弃。
如果,Q1和Q2都用相同的routingKey 绑定 X, 这个模式类似于Type是finout的exchange, Q1和Q2都会收到消息
topic 模式
相比于前一个,routingkey 支持模糊匹配。
- *(star) can substitute for exactly one word.
- #(hash) can substitute for zero or more words.
星号支持一个字段,井号支持0个或多个字段。
topic 模式多变:
- queue和exchange绑定的routingKey 设置为#, 相当于广播模式,exchange 的type 为finout
- queue和exchange绑定的routingKey 中不包含任何*或者#, 相当于exhange的type为direct
rpc 模式
待更新
参考文档
- https://www.rabbitmq.com/getstarted.html