The Work mode of Java RabbitMQ is to configure multiple consumers to consume messages from a single queue, which can improve the concurrent processing speed of messages. The architecture is as shown in the following diagram.
Note: Regardless of which work mode is used in RabbitMQ, each queue supports multiple consumers. For the same queue, a message will only be processed by one of the consumers.
1. Preliminary Tutorial
Please read the following sections first to understand the related knowledge.
- RabbitMQ Basic Concepts
- RabbitMQ Work Mode
- RabbitMQ Quick Start for Java (Mandatory, as subsequent sections will not repeat the code but only display key code)
2. Configuring Multiple Consumers
By using the RabbitListener annotation and configuring the concurrency parameter, you can start 10 consumers to concurrently process messages with the following code.
package com.tizi365.rabbitmq.listener;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
// Declare the message listener and specify the queue to listen to through the queues parameter
// Key parameter: concurrency represents the number of consumers that need to be started for the current listener, and its type is a string
@RabbitListener(queues = "hello", concurrency = "10")
public class HelloListener {
// Use RabbitHandler to mark the message handler, which is used to execute the message processing logic
@RabbitHandler
public void receive(String msg) {
System.out.println("Consumer - Received message '" + msg + "'");
}
}