I am trying to implement a functionality where a listener class I have can subscribe/unsubscribe to JMS topics. After some research there doesn't see to be a clear way to do this and I've come up with two solutions:
- Have a listener class which holds a list of String topic names and periodically run through all these topics its supposed to be subscribed to and run the blocking
jmsTemplate.receiveAndConvert(topicName)
on each (probably delegating the blocking operation itself to a worker pool). Subscribing/Unsubscribing from a topic would be as simple as removing a topic name from the list. Have a factory class which would build a new listener for each topic the application needs to subscribe to, using a method like:
public MessageListenerContainer createListener(String topic) { DefaultMessageListenerContainer container = new DefaultMessageListenerContainer(); container.setConnectionFactory(connectionFactory()); container.setDestinationName(topic); container.setMessageListener(new MyListenerClass()); return container;
}
The second option seems more elegant to me, but I am unsure of the lifecycle of the listeners. I went through a bit of the source for spring boot's jms and activemq modules and noticed that DefaultMessageListenerContainer
has methods initialize()
and start()
though I'm unsure how/if I need to use these, as the only way I could find a MessageListenerContainer
being built this way is as a Bean
declaration.
Also when unsubscribing from a topic, therefore wanting to destroy the listener container associated with it, is there more that needs to be done except calling the stop(callback)
method?
Is my understanding of JMS/ActiveMQ and its Spring integration correct in that there is no simpler way to achieve this? Is my approach correct?