本文实现多线程消费,其实原理就在同一个项目中建立多个@RabbitListener(queues = RabbitMqQueueConfig.FANOUT_EMAIL_QUEUE),多个消费者处理统一队列中的消息
其利用RabbitMq中SimpleRabbitListenerContainerFactory建立多个同一队列的监听连接

@Configuration
public class RabbitConsumerConfig {
    //并发数量
    public static final int DEFAULT_CONCURRENT = 5;
    @Bean("customContainerFactory")
    public SimpleRabbitListenerContainerFactory containerFactory(SimpleRabbitListenerContainerFactoryConfigurer configurer,
                                                                 ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConcurrentConsumers(DEFAULT_CONCURRENT);
        factory.setMaxConcurrentConsumers(DEFAULT_CONCURRENT);
        configurer.configure(factory, connectionFactory);
        return factory;
    }
}

将该多线程消费交给Spring管理
然后在消息监听类中使用自定义的连接工厂

@RabbitListener(queues = RabbitMqQueueConfig.FANOUT_EMAIL_QUEUE,containerFactory = "customContainerFactory")

消费结果如下图所示
在这里插入图片描述

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐