Spring Boot Multiple RabbitMQ Listeners to Single

2019-07-27 12:21发布

问题:

I am working on RabbitMQ using spring boot(Annotation based). I am trying to add multiple listeners to a single containers, but only one listener work.

I am able to initialize two containers and assign each container individual message Listener. Whether it is the only way to add multiple listener where each container have their respective listener? I am using ChannelAwareMessageListener interface, so that I can process the message individually and acknowledge them. I don't want to use RabbitListener because I cannot acknowledge the message.

    @Bean
    @Qualifier("receiverContainer")
    SimpleMessageListenerContainer receiverContainer(ConnectionFactory connectionFactory,@Qualifier("receiverAdapter") MessageListenerAdapter
listenerAdapter) {

        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setQueueNames(queueName);
        container.setMessageListener(listenerAdapter);
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        container.setAutoStartup(false);
        return container;
    }

In spring xml, I can add two listener to one container

<rabbit:listener-container
        connection-factory="connectionFactory" acknowledge="auto" concurrency="10"
        requeue-rejected="true">
        <rabbit:listener ref="myMessageListener" queues="spring.queue" />
        <rabbit:listener ref="messageQueueManager" queues="user.login.notification" />
    </rabbit:listener-container>

So how do I add two listener to one container in spring boot annotation based? Or I should go with one container-one listener way?

回答1:

No; only one listener per container is allowed.

When using the XML namespace, although it "looks" like there are multiple listeners, there is really a separate container for each <rabbit:listener/> element.

The <rabbit:listener-container/> parent element is just a convenient way to specify common container attributes for each container created by the child elements.