Tuesday, March 15, 2011

Messaging With WebSphere MQ Using Spring JMS

Spring JMS provides a simple API to work with JMS implementations. This post describes how to use Spring JMS to communicate with IBM WebSphere MQ. The code has been tested with WebSphere MQ version 7.0.1. Maven is used as the build tool. It is also used to resolve the WebSphere MQ and other dependencies. Only relevant code snippets are listed below - for the complete source, please refer to the link at the bottom of this post.

To start off we need to obtain the WebSphere MQ JARs. These JARs are proprietary - hence they will not resolve through a public Maven repository like Maven Central. These JARs need to be obtained from the WebSphere MQ installation directory and manually deployed to our local Maven repository. The config below defines the WebSphere MQ dependencies in our Maven POM file.

Spring's JMSTemplate class is the key to simplifying access to the conventional JMS API. It abstracts the common and repetitive boiler-plate code by handling the creation and closing of connections and sessions, sending and receiving of messages and handling of exceptions. JMSTemplate and a few other beans need to be defined in our Spring config.

MQQueueConnectionFactory defines the connection to the Queue Manager. Next we define SingleConnectionFactory102, DynamicDestinationResolver and finally JmsTemplate102. The 102 suffix implies that our underlying JMS implementation version is 1.0.2. Now that our configuration is complete, we can send and receive JMS messages.

To send a JMS message, we use the send(String destinationName, MessageCreator creator) method of JMSTemplate.

To receive a message, we use the receive(String destinationName) method.

As we can see, Spring's JMSTemplate really simplifies and speeds-up connecting to a JMS provider like WebSphere MQ.

Sample Source Code
A fully functional example Maven application accompanies this post. It provides the complete source code mentioned in this post. It can be downloaded at GitHub using the link below.