Golang RabbitMQ Routing Pattern
The routing pattern in RabbitMQ extends the exchange routing method on the basis of the publish-subscribe pattern. The exchange type for the routing pattern is direct, which is also the default exchange for RabbitMQ. In the previous sections, an explicit exchange was not used, but the underlying exchange used was actually a direct exchange.
Tip: If you are unfamiliar with the routing pattern rules, please read RabbitMQ Routing Patterns.
1. Prerequisite Tutorial
Please read the chapter on Golang RabbitMQ Publish-Subscribe Pattern first. Essentially, the various working modes of RabbitMQ are implemented by various types of exchanges. The code is almost the same, with the main difference being the definition of the exchange. Therefore, once the publish-subscribe pattern is understood, other patterns are quite simple.
2. Declaring a Direct Exchange
err = ch.ExchangeDeclare(
"tizi365_direct", // Exchange name, needs to be unique
"direct", // Exchange type
true, // Durable
false, // Auto-deleted
false, // Internal
false, // No-wait
nil, // Arguments
)
3. Sending Messages
// Message content
body := "Hello Tizi365.com!"
// Pushing the message
err = ch.Publish(
"tizi365_direct", // Exchange (exchange name)
"blog", // Routing key, a crucial parameter that determines which queue your message will be sent to
false, // Mandatory
false, // Immediate
amqp.Publishing {
ContentType: "text/plain", // Message content type, in this case, plain text
Body: []byte(body), // Message content
})
4. Consumer Receiving Messages
4.1. Binding the Exchange
// Declaring the queue to be operated on
q, err := ch.QueueDeclare(
"", // Queue name, if not specified, a random one will be generated
false, // Durable queue
false, // Delete when unused
true, // Exclusive
false, // No-wait
nil, // Arguments
)
// Binding the queue to the specified exchange
err = ch.QueueBind(
q.Name, // Queue name
"blog", // Routing key, if it matches the routing parameter specified when sending a message, the message is delivered to the current queue
"tizi365_direct", // Exchange name, which needs to be consistent with the exchange defined at the message sender's end
false,
nil)
4.2. Consuming Messages
// Creating a consumer
msgs, err := ch.Consume(
q.Name, // Reference to the earlier queue name
"", // Consumer name, if not filled, a random one will be generated
true, // Automatically acknowledge messages processed by the queue
false, // Exclusive
false, // No-local
false, // No-wait
nil, // Args
)
// Looping to consume messages in the queue
for d := range msgs {
log.Printf("Received message=%s", d.Body)
}