Saturday, 25 August 2012

JMS using Active MQ

Introduction
This article explains java messaging using active MQ. Using JMS, one program can send messages to another program. However the communication between these programs is not direct i.e here the messages from one program is sent to a queue and then the other program receives the message from this queue. (Below is the diagramatic view how jms works : ref http://docs.oracle.com/javaee/6/tutorial/doc/bnceh.html )

jms-programmingModel.gif

Downloading and Starting ActiveMQ

In this demonstration ,we will using Active MQ as a JMS provider.
You can download activeMQ from activeMQ site (http://activemq.apache.org ) . Once downloaded extract the zip to your local directory and start the activemq bat file from the bin directory.
start_acmq.jpg
Active MQ also provides an admin console from where you can get information about different topics , queues etc. You can get admin console by accessing http://localhost:8161/admin/

Sending and Receiving Messages using ActiveMQ

Since now we have our JMS provider i.e ActiveMQ running , let us write the code for producer and consumer. I prefer to use Eclipse IDE for Java programming . So just add activemq-all-5.3.0.jar (version may be different) in your classpath . This jar will be available in the zip that was downloaded earlier .




Connection that is used above represents the connection with the JMS provider.

The interesting part is that the producer is not all aware of who the consumer is . That is producer just sends out the messages to the queue (in our case its TEST_QUEUE) . Once the message is sent the producer is not bothered about what is being done with the message.
producer_console.JPG

producer_adminconsole.JPG

Below is the Consumer.java class which consumes the message from the queue.

consume_console.JPGconsumer_adminconsole.JPG
Conclusion:
Communication using JMS is asynchronous. The producer just sends a message and goes on with his business. JMS is a way of abstracting the process of sending messages. As seen above we are using some custom Queue ‘TEST_QUEUE’. Producer just sends the message to the queue and then its above what did consumer does with the message. Once the consume receives the message , we can do a lot of stuff like send the messages to some other queues, process and perform certain operations, store into database etc.

Here in this example , we demonstrated JMS using ActiveMQ in which we created a queue.
Producer sends the message to the queue and receiver receives it from the queue. Apart from Queue , we also have topic , where a producer can send message and many consumers can consume them. For a topic , we have to implement MessageListener and override onMessage() function.

No comments:

Post a Comment