The role of configuration configuration class, rabbitMq code example how to customize beans

@Configuration
@ConditionalOnClass(SimpleRabbitListenerContainerFactory.class)
public class ConsumerConfig {

@Value("${rabbit.batch.num:100}")
private int batchNum;

@Bean("batchQueueRabbitListenerContainerFactory")
public SimpleRabbitListenerContainerFactory batchQueueRabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
factory.setBatchListener(true);
factory.setConsumerBatchEnabled(true);
factory.setBatchSize(batchNum);
return factory;
}
}

This code is a RabbitMQ message consumer configuration class based on Spring Boot. Let me explain step by step and give examples:

    @Configuration: This annotation indicates that this is a configuration class, which will be scanned by the Spring container and load the bean definitions in it.

    @ConditionalOnClass(SimpleRabbitListenerContainerFactory.class): This annotation indicates that the configuration class will only take effect when SimpleRabbitListenerContainerFactory exists in the class path. Simply put, it is a conditional assembly that ensures that related beans will be created under specific conditions.

    ConsumerConfig class name: This is the name of the configuration class, used to identify this configuration class.

    @Value("${rabbit.batch.num:100}") private int batchNum;: This is a property injection, which means reading the property value named rabbit.batch.num from the configuration file, if it does not exist Use the default value of 100 and inject it into the batchNum variable.

    @Bean("batchQueueRabbitListenerContainerFactory"): This is a Bean definition, and the returned Bean name is batchQueueRabbitListenerContainerFactory. This method returns a Bean of type SimpleRabbitListenerContainerFactory.

    public SimpleRabbitListenerContainerFactory batchQueueRabbitListenerContainerFactory(ConnectionFactory connectionFactory): This is a factory method used to create SimpleRabbitListenerContainerFactory Bean. It requires a ConnectionFactory as a parameter, which is automatically injected by the Spring container.

    SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();: Create a SimpleRabbitListenerContainerFactory instance.

    factory.setConnectionFactory(connectionFactory);: Sets the connection factory for connecting to the RabbitMQ server.

    factory.setBatchListener(true);: Set to batch listening mode, indicating that the message consumption method is batch consumption.

    factory.setConsumerBatchEnabled(true);: Set the consumer batch mode to enable, allowing consumers to consume messages in batch mode.

    factory.setBatchSize(batchNum);: Set the number of messages consumed in batches. The batchNum attribute injected previously is used as the batch size.
          
              



Example:
Suppose you have an application that needs to consume messages in RabbitMQ and has certain performance requirements. You can use this configuration class to achieve batch consumption. Control the number of messages consumed in each batch by setting the rabbit.batch.num property to improve consumption efficiency.

Code relationship explains rabbitMq monitoring messages:

@Configuration
@ConditionalOnClass(SimpleRabbitListenerContainerFactory.class)
public class ConsumerConfig {

@Value("${rabbit.batch.num:100}")
private int batchNum;

@Bean("batchQueueRabbitListenerContainerFactory")
public SimpleRabbitListenerContainerFactory batchQueueRabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
factory.setBatchListener(true);
factory.setConsumerBatchEnabled(true);
factory.setBatchSize(batchNum);
return factory;
}
}
@Slf4j
@Component
@RequiredArgsConstructor
public class AssemblerMessageConsumer {

private final AssemblerMessageService assemblerMessageService;

@RabbitListener(queues = test.queue", containerFactory = "batchQueueRabbitListenerContainerFactory")
@RabbitHandler
public void onMessage(List<Message> messages) {
List<MessageDto> list = messages.stream().map(message -> (MessageDto) message.getPayload()).collect(Collectors.toList());
assemblerMessageService.handler(list);
}
}

These two pieces of code are about using Spring Boot to integrate RabbitMQ to realize the configuration and consumer code of message consumption. Let me explain their role and relationship one by one.

First of all, the ConsumerConfig class is a configuration class that uses the @ConditionalOnClass(SimpleRabbitListenerContainerFactory.class) conditional annotation to ensure that it will only take effect if the SimpleRabbitListenerContainerFactory class exists in the class path. This class defines a Bean named batchQueueRabbitListenerContainerFactory, which is used to create a SimpleRabbitListenerContainerFactory instance for batch message listening. During the initialization process of this Bean, it will read the property value named rabbit.batch.num in the configuration file as the default value of batchNum. If it is not configured, it will use the default value of 100, and then apply it to the created SimpleRabbitListenerContainerFactory.

Next, the AssemblerMessageConsumer class is a message consumer component. The listening queue is specified as “test.queue” through the @RabbitListener annotation, and the batchQueueRabbitListenerContainerFactory factory is used to create a message listening container. In this way, the consumption of batch messages in the “test.queue” queue is realized.

About the relationship between containerFactory and batchQueueRabbitListenerContainerFactory:

containerFactory is the parameter specified in the @RabbitListener annotation, which is used to specify the factory bean of the message listening container. Here, you tell Spring to use a factory bean named batchQueueRabbitListenerContainerFactory to create a message listening container by setting containerFactory = "batchQueueRabbitListenerContainerFactory".
batchQueueRabbitListenerContainerFactory is a batch message listening container factory Bean defined in the ConsumerConfig class. It will create a listening container capable of processing batch messages based on configuration parameters.

Regarding rabbitMq server-related configuration, whether it will be assigned to containerFactory after being automatically read when spring starts:

In the ConsumerConfig class, the attribute value named rabbit.batch.num is assigned to the batchNum variable through the @Value annotation, and then batchNum is applied to the created SimpleRabbitListenerContainerFactory during the initialization process of the batchQueueRabbitListenerContainerFactory Bean. Therefore, rabbitMq server-related configuration will be automatically read when Spring starts and passed to the message listening container through the batchQueueRabbitListenerContainerFactory factory bean.

Finally, what is the data printed by containerFactory:

Regarding why a ConnectionFactory Bean is created after these configuration information are automatically read at startup:
Since containerFactory is a factory bean of a message listening container, it does not print out data itself. Its function is to create a message listening container, and the message listening container will execute corresponding business logic when receiving a message, and may output logs, etc. Therefore, the actual data output should be output by the log.info statement in the onMessage method, and the output content is the JSON format string of the received message data.
In a Spring Boot application, the RabbitMQ connection information in the configuration file will be read by the Spring container and used to create a ConnectionFactory Bean. ConnectionFactory is an interface provided by the RabbitMQ Java client. It contains all the information required to establish a connection with the RabbitMQ server, such as host name, port, user name, password, etc.

When the Spring Boot application starts, Spring will automatically instantiate a ConnectionFactory Bean based on the information in the configuration file and incorporate it into the Spring application context for management. The advantage of this is that in components that need to communicate with RabbitMQ, the ConnectionFactory Bean can be injected directly without having to manually create a connection each time.

For example, in the RabbitMQ message listener configuration mentioned earlier, when the method identified by the @RabbitListener annotation needs to be connected to RabbitMQ, the ConnectionFactory can be injected into the method through Spring’s dependency injection mechanism to achieve connection with RabbitMQ and Message processing.

Therefore, when the RabbitMQ connection information in the configuration file is read, Spring will automatically create a ConnectionFactory Bean and inject it into the relevant components when needed to establish a connection and communicate with RabbitMQ.

About rabbitMq related configuration:
Configuration example using application.properties file:

# RabbitMQ connection configuration

spring.rabbitmq.host=your_rabbitmq_host
spring.rabbitmq.port=5672
spring.rabbitmq.username=your_rabbitmq_username
spring.rabbitmq.password=your_rabbitmq_password

Brothers, a reminder, this 5672 is the port connected to mq, and 15672 is the port of the visual backend. You must not correct the mistake.
Configuration example using application.yml file:

# RabbitMQ connection configuration

spring:
  rabbitmq:
    host: your_rabbitmq_host
    port: 5672
    username: your_rabbitmq_username
    password: your_rabbitmq_password

In this example, you need to replace “your_rabbitmq_host”, “your_rabbitmq_username” and “your_rabbitmq_password” with the hostname, port, username and password of the RabbitMQ server you are actually using.

Regarding the connection configuration of the RabbitMQ server, it is usually configured in the project’s configuration file (such as application.properties or application.yml). You can add the connection information of the RabbitMQ server in the configuration file, including host name, port, user name, password and other information. Spring Boot will automatically read these configuration information when it starts, create a ConnectionFactory Bean, and inject it into the place where RabbitMQ needs to be connected. In your batchQueueRabbitListenerContainerFactory method, by declaring parameters of the ConnectionFactory type, Spring will automatically inject the above configured connection factory into the method, thus ensuring the connection to the RabbitMQ server.
(When the Spring Boot application starts, these configurations will be automatically read and a connection to the RabbitMQ server will be created. In the code here, the connection factory ConnectionFactory will be automatically injected by Spring into the batchQueueRabbitListenerContainerFactory method to create a RabbitMQ connection.)