Golang RabbitMQ work mode, achieving concurrent consumption by multiple consumers.
Explanation:
P represents the producer, C1 and C2 represent consumers, and the red color represents the queue.
Tip: Each message can only be consumed by one consumer.
Pre-tutorial
Please read Golang RabbitMQ Quick Start Tutorial first to understand the basic operations of Golang on RabbitMQ. If you are not familiar with RabbitMQ, please read the previous chapters first.
Concurrent Consumption
Golang mainly uses goroutines to implement multiple consumers, below is the implementation of multiple consumers.
Tip: For how to send messages, please refer to Golang RabbitMQ Quick Start Tutorial.
```go
package main
import (
“log”
“time”
"github.com/streadway/amqp"
)
// Error handling
func failOnError(err error, msg string) {
if err != nil {
log.Fatalf(“%s: %s”, msg, err)
}
}
func main() {
// Connect to RabbitMQ
conn, err := amqp.Dial(“amqp://guest:guest@localhost:5672/“)
failOnError(err, “Failed to connect to RabbitMQ”)
defer conn.Close()
// Create 5 consumers through goroutines
for i := 0; i < 5; i++ {
go func(number int) {
// Create a rabbitmq channel for each consumer
ch, err := conn.Channel()
failOnError(err, "Failed to open a channel")
defer ch.Close()
// Declare the queue to be operated
q, err := ch.QueueDeclare(
"hello", // Queue name
false, // Durable
false, // Delete when unused
false, // Exclusive
false, // No-wait
nil, // Arguments
)
failOnError(err, "Failed to declare a queue")
// Create a consumer
msgs, err := ch.Consume(
q.Name, // Queue name to operate
"", // Consumer unique id, if not filled, a unique value is generated automatically
true, // Auto-acknowledge messages (i.e. automatically confirm that the message has been processed)
false, // Exclusive
false, // No-local
false, // No-wait
nil, // Args
)
failOnError(err, "Failed to register a consumer")
// Process messages in a loop
for d := range msgs {
log.Printf("[Consumer number=%d] Received message: %s", number, d.Body)
// Simulate business processing, sleep for 1 second
time.Sleep(time.Second)
}
}(i)
}
// Hang the main goroutine to prevent the program from exiting
forever := make(chan bool)
<-forever
}
```
Tip: Regardless of the type of exchange used by RabbitMQ, queues can have multiple consumers, and the way to start multiple consumers is the same as in this example.