Adding Dynamic Number of Listeners(Spring JMS)

一曲冷凌霜 提交于 2020-01-29 05:21:05

问题


I have a requirement to add multiple listeners as mentioned in the application.properties file. Like Below,

InTopics=Sample.QUT4,Sample.T05,Sample.T01,Sample.JT7

NOTE: This number can be lot more or less.

I am thinking of getting them in an array,

@Value("${InTopics}")
private String[] inTopics;

But i don't know how to create multiple listeners from the array.

Currently, for one Topic i am doing as below,

@Configuration
@EnableJms
public class JmsConfiguration {

@Value("${BrokerURL}")
private String brokerURL;

@Value("${BrokerUserName}")
private String brokerUserName;

@Value("${BrokerPassword}")
private String brokerPassword;

@Bean
TopicConnectionFactory connectionFactory() throws JMSException {
    TopicConnectionFactory connectionFactory = new TopicConnectionFactory(brokerURL, brokerUserName, brokerPassword);
    return connectionFactory;
}

@Bean
JmsListenerContainerFactory<?> jmsContainerFactory(TopicConnectionFactory connectionFactory) throws JMSException {
    SimpleJmsListenerContainerFactory factory = new SimpleJmsListenerContainerFactory();
    factory.setConnectionFactory(connectionFactory);
    factory.setPubSubDomain(Boolean.TRUE);
    return factory;
 }

}

And My Listener,

@JmsListener(destination = "${SingleTopicName}", containerFactory = "jmsContainerFactory")
public void receiveMessage(Message msg) {
   //Do Some Stuff
}

Is there any way i can achieve this?


回答1:


You can't do it with annotated @JmsListeners but you can register each listener programmatically by extending JmsListenerConfigurer as described in the reference documentation.

EDIT

Since you are injecting the property as an array...

@Value("${InTopics}")
private String[] inTopics;

Spring will split up the list an create an array based on the number of queues in the list.

You can then iterate over the array in JmsListenerConfigurer.configureJmsListeners() and create an endpoint for each element in the array - you don't need to know ahead of time how big the array is.

for (String inTopic : inTopics) {
    ...
}


来源:https://stackoverflow.com/questions/34063230/adding-dynamic-number-of-listenersspring-jms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!