pike
pike

Reputation: 711

AMQP async listener starts listening to message only after an event happens

I currently have an AMQP async listener that is listening to messages on a queue automatically.

However, my requirement is that I shouldn't have this listener listening to messages until a certain event has happened. For event, I am thinking of using @EventListener annotation.

The async listener looks like this:

@Configuration
public class ExampleAmqpConfiguration {

    @Bean
    public SimpleMessageListenerContainer messageListenerContainer() {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(rabbitConnectionFactory());
        container.setQueueName("some.queue");
        container.setMessageListener(exampleListener());
        return container;
    }

    @Bean
    public ConnectionFactory rabbitConnectionFactory() {
        CachingConnectionFactory connectionFactory =
            new CachingConnectionFactory("localhost");
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        return connectionFactory;
    }

    @Bean
    public MessageListener exampleListener() {
        return new MessageListener() {
            public void onMessage(Message message) {
                System.out.println("received: " + message);
            }
        };
    }
}

I was thinking of adding the @EventListener to the method messageListenerContainer() so it looks like this:

@Bean
@EventListener
public SimpleMessageListenerContainer messageListenerContainer(CustomeEvent customEvent) {
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
    container.setConnectionFactory(rabbitConnectionFactory());
    container.setQueueName("some.queue");
    container.setMessageListener(exampleListener());
    return container;
}

However, the messageListenerContainer() bean just seems to run at start up, regardless of the EventListener.

What is proper way for this async listner to listen to messages, only after a CustomEvent happens?

Thanks.

Upvotes: 0

Views: 908

Answers (1)

Gary Russell
Gary Russell

Reputation: 174554

Set the containers autoStartup property to false.

In your @EventListener, auto wire the container and start() it.

EDIT

public class MyEventListener {

    @Autowired
    private SimpleMessageListenerContainer container;

    @EventListener
    public void someEvent(MyEvent event) {
        this.container.start();
    }

}

and

@Bean
public MyEventListener listener() {
    return new EventListener();
}

Upvotes: 2

Related Questions