2015-09-21 75 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

相關問題