GrabDuck

Getting started with Java Messaging Service (JMS)

:

This blog will basically focus on the practical implementation of JMS. Here we will create a sample application with sender and receiver flow in eclipse. But before that some basics of JMS needs to be cleared.

What is JMS?

Java Message Service (JMS) is an application program interface (API) from Sun Microsystems that supports the messaging communication between computers / applications / software components in a network.
The messages involved exchange crucial data between computers – rather than only between users – and contain information such as event notification and service requests.
This API allows Java based applications to create, send, receive and read messages without exposing any client architecture information. JMS architecture is very loosely coupled unlike RMI where the remote method name is needed in order to communicate.
Two basic architecture is used for communication:
i. QUEUE – This is a kind of pipeline connection between two clients. For example, One-To-One chat where one client sends a message and the other one receives that.
ii. TOPIC – This can be considered as a common space where all the clients connected to the particular topics can communicate with each other. For example, Group chat where one client sends a message and all the connected clients receives that.
(Reference: http://java.sun.com/developer/technicalArticles/Ecommerce/jms/)

What is Apache ActiveMQ?

ActiveMQ is an open-source, messaging software which serve as the backbone for an architecture of distributed applications built upon messaging. ActiveMQ completely implements Java Messaging Service 1.1 (JMS). In order to run a JMS application we need ActiveMQ instance running on a machine which will be treated as a JMS server.
(Reference: http://activemq.apache.org)

STEPS TO CREATE JMS SAMPLE APPLICATION
We will be using Eclipse IDE for this application. Below are the steps to develop the application.

1. The first step to create a JMS application is to get Apache ActiveMQ.
Download apache-activemq-5.4.3 from http://activemq.apache.org/activemq-543-release.html depending on the operating system. Just extract the compressed file move to apache-activemq-5.4.3\bin\ folder and start the server using activemq.bat or activemq.sh file.
The server should start without any issue. To test whether the server is running or not, browse http://localhost:8161.

2. Create a “Java Project” in eclipse, name it as “JMSSampleApplication“.

3. Create a package structure inside the “src” folder. It may be something like “com.mindfire.jms“.

4. Create a class inside that package. Name the class as “Sender“.

5. Now add the below code to the class.


import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;

import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.QueueSender;
import javax.jms.DeliveryMode;
import javax.jms.QueueSession;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;

public class Sender {

	public static void main(String[] args) throws Exception {
		Properties env = new Properties();
		env.put(Context.INITIAL_CONTEXT_FACTORY,
				"org.apache.activemq.jndi.ActiveMQInitialContextFactory");
		env.put(Context.PROVIDER_URL, "tcp://localhost:61616");
		env.put("queue.queueSampleQueue", "MyNewQueue");
		
		// get the initial context
		InitialContext ctx = new InitialContext(env);

		// lookup the queue object
		Queue queue = (Queue) ctx.lookup("queueSampleQueue");
		// lookup the queue connection factory
		QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.lookup("QueueConnectionFactory");
		// create a queue connection
		QueueConnection queueConn = connFactory.createQueueConnection();

		// create a queue session
		QueueSession queueSession = queueConn.createQueueSession(false,Session.DUPS_OK_ACKNOWLEDGE);

		// create a queue sender
		QueueSender queueSender = queueSession.createSender(queue);
		queueSender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

		// create a simple message to say "Hello"
		TextMessage message = queueSession.createTextMessage("Hello");

		// send the message
		queueSender.send(message);

		System.out.println("sent: " + message.getText());

		queueConn.close();
	}
}

6. Create another class inside that package. Name the class as “Receiver”.

7. Now add the below code to the class.


import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;

import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.QueueSession;
import javax.jms.QueueReceiver;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;

public class Receiver {

	public static void main(String args[]) throws Exception {
		Properties env = new Properties();					   				env.put(Context.INITIAL_CONTEXT_FACTORY,
				"org.apache.activemq.jndi.ActiveMQInitialContextFactory");
		env.put(Context.PROVIDER_URL, "tcp://localhost:61616");
		env.put("queue.queueSampleQueue","MyNewQueue");
		// get the initial context
		InitialContext ctx = new InitialContext(env);

		// lookup the queue object
		Queue queue = (Queue) ctx.lookup("queueSampleQueue");

		// lookup the queue connection factory
		QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.lookup("QueueConnectionFactory");

		// create a queue connection
		QueueConnection queueConn = connFactory.createQueueConnection();

		// create a queue session
		QueueSession queueSession = queueConn.createQueueSession(false,Session.AUTO_ACKNOWLEDGE);

		// create a queue receiver
		QueueReceiver queueReceiver = queueSession.createReceiver(queue);

		// start the connection
		queueConn.start();

		// receive a message
		TextMessage message = (TextMessage) queueReceiver.receive();

		// print the message
		System.out.println("received: " + message.getText());

		// close the queue connection
		queueConn.close();
	}
}

8. Now we need to resolve all the import errors in both the classes. Inside apache-activemq-5.4.3 folder, we have a activemq-all-5.4.3.jar file. Add this jar file to the project build path. Perform the below steps.
i. Right click on “JMSSampleApplication” project.
ii. Build Path —> Configure Build Path…
iii. Move to “Libraries” tab. Click on “Add External JARs“.
iv. Browse to “activemq-all-5.4.3.jar” file and open.
Hopefully this will resolve all the import issue.

9. First run Sender.java. This will send “Hello” message to the queue.

10. Then run Receiver.java. This will receive the “Hello” message from the queue.

This is a simple JMS application with synchronous receiver.

Happy Coding… 🙂
Rupal Chatterjee
Software Engineer, Mindfire Solutions
http://www.mindfiresolutions.com
images
Connect me on Google, Facebook