2015-09-21 74 views
4

我有一个Spring应用程序,它具有用Spring的@JmsListener注释的方法。该应用程序部署在多个节点上。在某些特定节点上,我需要禁用JMS侦听器,以便它不会将消息从队列中拉出。如何在启动时以编程方式禁用Spring @JmsListener

似乎有一种方法可以在应用程序启动后停止侦听器。但是这似乎在启动和禁用代码在应用程序实例可能使用消息的位置运行时留下了简短的窗口。相反,有没有办法在应用程序启动过程中禁用侦听器。

回答

4

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

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

setAutoStartup(false); 

需要通过获得通过JmsListenerEndpointRegistry 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. 
... 
+0

我看不到我如何调用DefaultMessageListenerContainer.setAutoStartup(false)。我正在使用Java Config并拥有一个@Bean,它提供了一个如文档中所示的DefaultJmsListenerContainerFactory。但是工厂没有setAutoStartup方法。 – sudr

+0

是的,它位于超类'AbstractJmsListenerContainerFactory';它在创建容器时传播到实际的侦听器容器。参见'createListenerContainer()'。 –

+0

感谢您的确认。我发现这是在Spring 4.2中添加的,如https://jira.spring.io/browse/SPR-12824 – sudr

相关问题