默认情况下,Rabbitmq消费者为单线程串行消费,这也是队列的特性,当然在有些业务中需要并发消费,本文主要示例spring中和boot中指定消费者数量来并发消费。spring amqp文档也有相关描述:文档地址
通过设置Messagelistener 的containerconcurrency属性来设置消费者数量
XML示例:
<rabbit:listener-container connection-factory="connectionFactory" acknowledge="manual" concurrency= "5">
<rabbit:listener ref="myMessageListener" queue-names="hello"/>
</rabbit:listener-container>
Boot中消费者配置可以参考前面文章,但是在@RabbitListener中,concurrency并不是配置在注解中,而且通过配置containerFactory来设置:
定义containerFactory bean:
@Bean("pointTaskContainerFactory")
public SimpleRabbitListenerContainerFactory pointTaskContainerFactory(SimpleRabbitListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setPrefetchCount(PointTaskConstant.DEFAULT_PREFETCH_COUNT);
factory.setConcurrentConsumers(PointTaskConstant.DEFAULT_CONCURRENT);
configurer.configure(factory, connectionFactory);
return factory;
}
/**
* 消费者数量,默认10
*/
public static final int DEFAULT_CONCURRENT = 10;
/**
* 每个消费者获取最大投递数量 默认50
*/
public static final int DEFAULT_PREFETCH_COUNT = 50;
@RabbitListener(queues = MQConstant.POINT_TASK_QUEUE_NAME,containerFactory = "pointTaskContainerFactory")
MQConstant.POINT_TASK_QUEUE_NAME 为队列名称,常量,自定义
在多消费同时消费情况下,必须要考虑到多线程安全问题。