Spring: Handling incoming JMS messages asynchronously
Handling incoming JMS messages in an asynchronous manner requires, implementing a MessageListener, creating a connection, starting a thread, handling connection loss and thread death, etc…
Spring’s MessageListenerContainers provide a “Message Driven Pojo” framework that handles all that for you except implementing the MessageListener.
To take advantage of this you first need to create JMS connection factory and Destination:
<bean id="connectionPool" class="org.springframework.jms.connection.SingleConnectionFactory"> <property name="targetConnectionFactory"> <bean class="org.apache.activemq.ActiveMQConnectionFactory"> <property name="brokerURL" value="tcp://localhost"/> </bean> </property> </bean> <bean id="messageDestination" class="org.apache.activemq.command.ActiveMQQueue"> <constructor-arg value="MY.INCOMING" /> </bean>
Then implement the MessageListener interface:
@Component("IncomingMsgProcessor")
public class IncomingMsgProcessor implements MessageListener {
@Override
public void onMessage(Message message)
{
//Your message handling code here
}
}
And finally inject an instance into the MessageListenerContainer:
<bean id="incommingMessageListenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer"> <property name="connectionFactory" ref="connectionPool" /> <property name="destination" ref="messageDestination" /> <property name="messageListener" ref="IncomingMsgProcessor" /> <!-- Retry connection every 10 seconds. --> <property name="recoveryInterval" value="10000" /> </bean>
org.springframework.jms.listener.DefaultMessageListenerContainer gives a nice set of features, but spring offers other implementations if more (or less) is needed. If your message listener needs access to the JMS session you can implement SessionAwareMessageListener which has a method that take the message and session onMessage(Message message, Session session) instead.