I'm looking into JMS using Spring and wish to create a some concurrent consumers of a particular queue when my MVC webapp starts up.
I've seen the following XML config elsewhere on SO (https://stackoverflow.com/a/6861144):
<jms:listener-container concurrency="10">
<jms:listener destination="some.queue" ref="fooService" method="handleNewFoo"/>
</jms:listener-container>
I'm using Spring configuration in Java as opposed to XML. Can someone please help out with the syntax for Spring annotation?
My existing JmsConfiguration.java looks like:
@Configuration
@ComponentScan(basePackages="net.domain.orders")
public class JmsConfiguration {
@Bean
public JmsTemplate jmsTemplate() {
JmsTemplate jmsTemplate = new JmsTemplate();
jmsTemplate.setDefaultDestination(new ActiveMQQueue("orders.queue"));
jmsTemplate.setConnectionFactory(connectionFactory());
return jmsTemplate;
}
@Bean
public ActiveMQConnectionFactory connectionFactory() {
ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory();
activeMQConnectionFactory.setBrokerURL("tcp://localhost:61616");
return activeMQConnectionFactory;
}
}
I have searched many examples but all I have found so far are XML-based.
The @JmsListener is the only annotation required to convert a method of a normal bean into a JMS listener endpoint.
A message listener container is used to receive messages from a JMS message queue and drive the MessageListener that is injected into it. The listener container is responsible for all threading of message reception and dispatches into the listener for processing.
Create a Spring JMS Listener To create a JMS listener you need to implement the MessageListener interface. It has an onMessage() method that is triggered for each message that is received. The below StatusMessageListener tries to cast the received message to a TextMessage .
The JmsTemplate class is used for message production and synchronous message reception. For asynchronous reception similar to Java EE's message-driven bean style, Spring provides a number of message listener containers that are used to create Message-Driven POJOs (MDPs). The package org. springframework.
You want DefaultMessageListenerContainer
:
@Bean
public DefaultMessageListenerContainer jmsListenerContainer() {
DefaultMessageListenerContainer dmlc = new DefaultMessageListenerContainer();
dmlc.setConnectionFactory(connectionFactory());
dmlc.setDestination(new ActiveMQQueue("orders.queue"));
// To schedule our concurrent listening tasks
dmlc.setTaskExecutor(taskExecutor());
// To perform actual message processing
dmlc.setMessageListener(messageListener());
dmlc.setConcurrentConsumers(10);
// ... more parameters that you might want to inject ...
return dmlc;
}
Read the JMS namespace documentation for information about mapping XML parameters to Java parameters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With