RabbitMQ is a powerful message broker that supports various messaging patterns, including the consumer group pattern. In Go, you can utilize the RabbitMQ Go client to set up consumer groups. This allows multiple consumers to share a queue, enabling load balancing and fault tolerance.
To implement consumer groups with RabbitMQ in Go, you first need to install the RabbitMQ client library. You can do this by running:
go get github.com/streadway/amqp
Here is a simple example demonstrating how to set up consumer groups with RabbitMQ using Go:
package main
import (
"log"
"github.com/streadway/amqp"
)
func main() {
conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
if err != nil {
log.Fatalf("Failed to connect to RabbitMQ: %s", err)
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
log.Fatalf("Failed to open a channel: %s", err)
}
defer ch.Close()
q, err := ch.QueueDeclare(
"task_queue", // name
false, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
if err != nil {
log.Fatalf("Failed to declare a queue: %s", err)
}
msg := "Hello World!"
ch.Publish(
"", // exchange
q.Name, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
DeliveryMode: amqp.Transient, // 1 = non-persistent, 2 = persistent
ContentType: "text/plain",
Body: []byte(msg),
})
log.Printf(" [x] Sent %s", msg)
// Start consuming messages
msgs, err := ch.Consume(
q.Name, // queue
"", // consumer
true, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // arguments
)
if err != nil {
log.Fatalf("Failed to register a consumer: %s", err)
}
// Handle messages
go func() {
for d := range msgs {
log.Printf("Received a message: %s", d.Body)
}
}()
log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
select {}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?