How to disable Spring @JmsListener programmatically on startup
Asked Answered
I

1

10

I have a Spring application that has methods annotated with Spring's @JmsListener. The application is deployed on multiple nodes. On some specific nodes I need to disable the JMS listener so that it is not pulling messages off the queue.

There appears to be a way to stop the listener after the application has started up. But this appears to leave open the brief window between startup and when the disable code runs where the application instance may consume messages. So instead is there a way to disable the listener during application startup.

Iliac answered 21/9, 2015 at 22:32 Comment(0)
G
9

You need to customize the listener container definitions created by the annotation.

Add a listener container factory @Bean (see the documentation) and set the autoStartup property to false.

setAutoStartup(false);

You can then start each container as needed by getting a reference via the JmsListenerEndpointRegistry bean. The containers are not beans themselves - from its javadoc...

...
* <p>Contrary to {@link MessageListenerContainer}s created manually, listener
* containers managed by registry are not beans in the application context and
* are not candidates for autowiring. Use {@link #getListenerContainers()} if
* you need to access this registry's listener containers for management purposes.
* If you need to access to a specific message listener container, use
* {@link #getListenerContainer(String)} with the id of the endpoint.
...
Giant answered 22/9, 2015 at 14:7 Comment(3)
I don't see how I can invoke DefaultMessageListenerContainer.setAutoStartup(false). I'm using Java Config and have a @Bean that provides a DefaultJmsListenerContainerFactory as shown in the documentation . But the factory does not have a setAutoStartup method.Iliac
Yes it does; it's on the superclass AbstractJmsListenerContainerFactory; it's propagated to the actual listener container when the container is created. See createListenerContainer().Giant
Thanks for confirming. I see this was added in Spring 4.2 as noted here jira.spring.io/browse/SPR-12824Iliac

© 2022 - 2024 — McMap. All rights reserved.