如何在启动时以编程方式禁用Spring @JmsListener

时间:2015-09-21 22:32:53

标签: spring-jms

我有一个Spring应用程序,其中的方法使用Spring的@JmsListener进行注释。该应用程序部署在多个节点上。在某些特定节点上,我需要禁用JMS侦听器,以便它不会将消息从队列中拉出来。

应用程序启动后似乎有一种方法可以停止监听器。但这似乎在启动和禁用代码运行之间打开了一个简短的窗口,其中应用程序实例可能会消耗消息。因此,有一种方法可以在应用程序启动期间禁用侦听器。

1 个答案:

答案 0 :(得分:4)

您需要自定义由注释创建的侦听器容器定义。

添加侦听器容器工厂@Bean(请参阅the documentation)并将autoStartup属性设置为false

setAutoStartup(false);

然后,您可以根据需要通过JmsListenerEndpointRegistry bean获取引用来启动每个容器。容器本身不是bean - 来自它的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.
...