javaspringspring-bootrabbitmqspring-amqp

DirectRabbitListenerContainerFactory vs DirectMessageListenerContainer


What is the difference in using this

    @Bean
    public DirectRabbitListenerContainerFactory rabbitListenerContainerFactory(final ConnectionFactory customConnectionFactory,final ThreadPoolTaskExecutor taskExecutor) {

        final DirectRabbitListenerContainerFactory factory = new DirectRabbitListenerContainerFactory();
        factory.setConnectionFactory(customConnectionFactory);
        factory.setMessageConverter(jsonMessageConverter());
        factory.setDefaultRequeueRejected(false);
        factory.setTaskExecutor(taskExecutor);
        factory.setPrefetchCount(prefetch);
        return factory;
    }

Versus this one

    @Bean
    public DirectMessageListenerContainer directMessageListenerContainer(ConnectionFactory customConnectionFactory) {
        DirectMessageListenerContainer container = new DirectMessageListenerContainer();
        container.setConnectionFactory(customConnectionFactory);
        // Add any other configuration settings as needed
        return container;
    }

And how do I add the direct message listener to my async rabbit template?

    @Bean
    public AsyncRabbitTemplate asyncRabbitTemplate(final RabbitTemplate customRabbitTemplate,final DirectMessageListenerContainer directMessageListenerContainer) {
        return new AsyncRabbitTemplate(customRabbitTemplate,directMessageListenerContainer);
    }

Solution

  • Usually, the RabbitListenerContainerFactory is used only for the @RabbitListner. For use-cases like that AsyncRabbitTemplate. it is better to rely on the DirectMessageListenerContainer.

    I'm not sure in your second question. What you have so far in your config is OK. Here is some gist from our tests:

        @Bean
        @Primary
        public SimpleMessageListenerContainer replyContainer(ConnectionFactory connectionFactory) {
            SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
            container.setReceiveTimeout(10);
            container.setAfterReceivePostProcessors(new GUnzipPostProcessor());
            container.setQueueNames(replies().getName());
            return container;
        }
    
        @Bean
        public AsyncRabbitTemplate asyncTemplate(@Qualifier("template") RabbitTemplate template,
                SimpleMessageListenerContainer container) {
    
            return new AsyncRabbitTemplate(template, container);
        }
    

    From AsyncRabbitTemplate no difference if that container is simple or direct.