Start and Stop JMS Listener using Spring

2019-01-25 12:39发布

问题:

So question is how to temporary stop and start a jms listener created using spring using the fallowing way :

<amq:connectionFactory id="exampleJmsFactory" brokerURL="tcp://${jms.broker.url}" />

<jms:listener-container concurrency="1" connection-factory="exampleJmsFactory"  destination-type="queue" message-converter="exampleMessageConverter">
        <jms:listener destination="incoming.example.client.queue" ref="exampleProductsMessageConsumer" method="consume"/>
</jms:listener-container>


<bean id="exampleProductsMessageConsumer" class="com.unic.example.jms.receive.JmsExampleProductsMessageConsumer" scope="tenant"/>

So basically what is the problem. We do have an init/update mechanism that the client can run in any time and durring this init/update I want to stop consuming of ANY messages because the system is unusable in this time and if a message came it will be lost.

So how I can stop the listener or the listener container or the whole connection using the API. I found that a class AbstractJmsListeningContainer have stop/start but how I can get it ? I mean none of this jms: listener and listener-containers have a name or anything like that.

回答1:

You can assign an id to the listener-container. Then get a reference to it, either by calling getBean or getting it injected. This will give you a AbstractJmsListeningContainer on which you can call start / stop.



回答2:

Yes thats do the trick.

<jms:listener-container concurrency="1" connection-factory="exampleJmsFactory"  destination-type="queue" message-converter="exampleMessageConverter">
        <jms:listener id="exampleProductsMessageListener" destination="incoming.example.client.queue" ref="exampleProductsMessageConsumer" method="consume"/>
</jms:listener-container>



DefaultMessageListenerContainer exampleProductsMessageListener= Registry.getApplicationContext().getBean("exampleProductsMessageListener", DefaultMessageListenerContainer.class);
exampleProductsMessageListener.stop();


回答3:

You can also get a hold of the messageListenerContainer, and invoke stop() on it:

@javax.annotation.Resource //autowire by name
 private AbstractJmsListeningContainer myMessageListenerContainer;

 myMessageListenerContainer.stop();

 I'm using the more verbose setup of this container:
 <bean id="myMessageListenerContainer" class="org.springframework.jms.listener.DefaultMes sageListenerContainer">
 <property name="connectionFactory" ref="jmsConnectionFactory"/>
 <property name="destination" ref="myQueue"/>
 <property name="messageListener" ref="myListener"/>
 <property name="autoStartup" value="true" />
 </bean>

Here you see that you can set autoStartup to false if you don't want the listenerContainer to automatically start.