Thursday, December 17, 2009

How to write a message driven pojo (MDP)

MDP is very simple to write in spring. There are quite a few examples out there. Follow these simple steps

Step1: Write a java class which implements javax.jms.MessageListener interface and implement the onMessage method

public class MyMessageListener implements javax.jms.MessageListener{

public void onMessage(Message message) throws RuntimeException{
// do what you have to here
}catch(Throwable ex) {
throw new RuntimeException(ex);

Step2: Add the bean to your spring context.
In your spring context XML file that you have defined add the following entry. if you are using anotation then this is optional

<bean id="myListener" class="MyMessageListener"/>

Step3: Add a jms connection factory
Connection factories can been directly defined in the spring context in which case you need to also define the connection pooling. If your application is going to reside in an
application server then you can use JNDI to get the connection factory. If you are using the second approach you define the jndiTemplate then the connection factory

<bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate"/>
<bean id="jmsQueueConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate">
<ref bean="jndiTemplate"/>
<property name="jndiName">

Where jms/QueueConnectionFactory is defined as a resouce in the application server along with connection pool settings.

Step4: Add the jms container to your spring context XML file.
This step attaches your POJO to a specific JMS resource (Queue/Topic)

<bean id="myJmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="jmsQueueConnectionFactory"/>
<property name="destinationName" value="MyExampleQ"/>
<property name="sessionTransacted" value="false"/>
<property name="messageListener" ref="myListener" />
<property name="concurrentConsumers" value="1" />
<property name="receiveTimeout" value="30000" />

And there you have it a simple message driven POJO called myListener mapping to the class MyMessageListener. It listens to messages in the queue named MyExampleQ
this is mentioned in the property destinationName. In this example sessionTransacted is set to false which means that if an exception occurs in onMessage method
the message will not be rolledback i.e. the message will be removed from the queue even if onMessage method failed. In most cases you might want the message to remain
in the queue if your operations in onMessage failed, in which case you need to set the value to true.

In this example concurrentConsumers is set to one you can use this property to better your performance by increasing this value.


madhu said...
This comment has been removed by the author.
madhu said...

How do u post values to 'MyExampleQ;

Steps to test this functionality???