Blog Image

Java Message Service  

This Blogs gives an brief explanation of Java Message Service. Along with that i just take an example by using Active MQ server which is provided by the Apache foundation. JMS is nothing but a loosely coupled communication Asynchronous messaging along with that the Reliable delivery.

JMS stands for Java Messaging service.

The Java Message Service (JMS) is a Java Message Oriented Middleware (MOM) API for sending messages between two or more clients. JMS is a part of the Java Enterprise Edition.

A specification that describes a common way for Java programs to create, send, receive and read distributed enterprise messages. Which is loosely coupled communication Asynchronous messaging along with that the Reliable delivery.

In JMS technology, one system can communicate with other system even though they are not connected with each other. In the absence of one system one system can communicate with other system by using Stored and Forward technology.

that means there some third party or some infrastructure which is place in between these two party i.e sender and receiver. That infrastructure or third person is nothing but Messaging Store.

Let’s consider there are two system one is sender system and another one is receiver system. My sender wants to communicate with the receiver that’s why whatever data with which sender wants to communicate with the receiver first he will place in some Messaging store, the Messaging Store will keeps hold of data and till the other system or receiver has been bring back. when the presence of the second system is present, at that time the message that has been stored in the “Messaging store” will be forwarded to the other system.

So that the other system starts using the data and performs the operation again it sends the response back to the first system by putting in the “Messing Store”. so that the “Messaging Store” forwards the response back to the first system which ever wants to read data.

That means one system does not need to know the address of other system or don’t need to connect to other system for communicating with each other. The complete infrastructure is nothing but JMS.

That means JMS is nothing but a Loosely Coupled or Disconnected Distributed communication.


The JMS basically supports two ways of communications

Communication Model

 1.point-point-point model

  2.multi-point model

1.point-to-point model

Suppose there is an application which wants communicate with the other one. Then the first application has to forward the request to the “Messaging Store”. When the first application is sending the messages by placing in the “Messaging Store”, then only one person can receive the messages rather than multiple people.


Let us say for this messaging store multiple people get registered means Application#2 and Application#3 wants to read the messages from the store. When the Application#1 sends the request, then one of them (Application#2 and Appliacation#3) receives the messages at a time, which is called point-to-point communication model.

In PTP model, one message is delivered to one receiver only. Here, Queue is used as a message oriented middleware (MOM).

The Queue is responsible to hold the message until receiver is ready. In PTP model, there is no timing dependency between sender and receiver.


A queue might have more than one sender & more than one receiver, but only one receiver may consume each message.

2)multi-point model / Publisher/Subscriber (Pub/Sub) Messaging Domain

Suppose Application#1 sends the messages to the “Messaging Store”, then the people who have registered with this store will get a chance to read the messages at least for once. That means the messages which the Application#1 has already sent will receive by all the applications who has registered for that messaging store, which is called as multi-point communication model.

In Pub/Sub model, one message is delivered to all the subscribers. It is like broadcasting. Here, Topic is used as a message oriented middleware that is responsible to hold and deliver messages.

In PTP model, there is timing dependency between publisher and subscriber.



Each message published to a topic is broadcast to all the clients that subscribe to this topic

JMS Components

JMS Provider: The messaging system (MOM) that implements JMS in addition to other administrative and control functionality required of a full-featured messaging product(IBM MQ, Active MQ). A message broker or agent(like a post office/postman).

JMS clients: Java applications that produce or receive messages.

JMS Producer / Publisher: A JMS client that creates and sends messages.

JMS Consumer/ Subscriber: A JMS client that receives messages.

JMS Application: The system composed of many JMS clients and typically one JMS provider.

 

MOM Service Providers

MOM Service Provider Products           Company

Weblogic                                                  Oracle

MQSeries                                                 IBM

JBOSSMQ                                               JBOSS

SoniqMQ                                                 Progress

TIBCO EMS                                           TIBCO

http://www-us.apache.org/dist/activemq/                                               Apache

For example,

IBM has provided IBM MQ Series Server that acts as Messaging Provider. Messaging provider will decide to how many people the messages will get send.

Suppose one application wants to send the messages to the other applications and it will decide on the communication model we have chosen.

We need to tell to the messaging provider. Messaging Provider need some data structure to store the messages and send.

There will be two types of objects depends on the communication model we wants to use (point-to-point and multi-point). If we want point-to-point, then we need to create “queue” type of distribution channel and similarly if we want multi-point, then we need to create “topic” type of distribution channel. So that the messaging objects are two types.                                                                                                      1.queue       2.topic

Queue:



Since queue is FIFO, so the messages that has been place first will be deliver in the first order. It is used for point-to-point communication.

For the queue we have to give the name, because there may be multiple queues. The client who puts the message in the queue is called “Queue Sender” and who receives the message in the queue is called “Queue Receiver”.

In the above diagram client1 is Queue Sender and client2 is Queue Receiver.

Queue Sender goes to the messaging provider, place the messages. When a message arrives into the queue, the messaging provider gets activated then he forwards the message to only one messaging receiver. The message that is there in the queue never gets forwarded to multiple message receivers. In this way we can achieve point-to-point communication.

Topic:


In case of multi-point model, there will messaging provider and inside that there will be topic with a given name, because there may be multiple topics.

With this topic we can publish the messages and there may be multiple people who are subscribing the messages and the messages that are inside the topics will gets forward to all people.

The people who put the message to the topic is called “Topic Publishers“ or “Topic Subscribers” or Topic Publisher Model. For a topic there may be any number of subscriber will be there. So that topic is multi-point communication.

 

The JMS API Programming Model

JMS Client

InitialContext jndiContext=new InitialContext();

//look up for the connection factory

ConnectionFactory cf=jndiContext.lookup(connectionfactoryname);

//create a connection

Connection connection=cf.createConnection();

//create a session

Session session=connection.createSession(false,Session.AUTO_ACKNOWLEDGE);

//create a destination object

Destination dest1=(Queue) jndiContext.lookup(“/jms/myQueue”); //for PointToPoint

Destination dest2=(Topic)jndiContext.lookup(“/jms/myTopic”); //for publish-subscribe

Producer

àSetup connection and create a session

àCreating producer-MessageProducer producer=session.createProducer(dest1);

àSend a message- Message m=session.createTextMessage();

                m.setText(“just another message”);

                producer.send(m);

àClosing the connection: connection.close();

Consumer Synchronous

àSetup connection and create a session

àCreating consumer-MessageConsumer consumer=session.createConsumer(dest1);

àStart receiving messages: connection.start();

                           Message m=consumer.receive();

Consumer Asynchronous

    àSetup the connection, create a session

    à Create consumer

    à Registering the listener: MessageListener listener=new myListener();

                              consumer.setMessageListener(listener);

 

    àmyListener should have onMessage()

  public void onMessage(Message msg){

        //read the message and do computation

    }

JMS integration framework:

Spring provides a JMS integration supports that simplifies the use of the JMS API as like Spring's integration does for the JDBC API.

JMS can be roughly divided into two areas of functionality, these are the production and consumption of messages.

The JmsTemplate class is used for message production and synchronous message reception.

For asynchronous reception similar to Java EE's message-driven bean(MDB) style, Spring provides a number of message listener containers that are used to create Message-Driven POJOs (MDPs).

So lets discuss what is message driven bean?

The MDB is designed for the client to invoke server side business logic using asynchronous communication. The MDB contains the business logic but it can be invoked by passing the message. So its as like JMS receiver. MDB asynchronously receive the message from queue and topic then process it.



First of all we need to download Active MQ server provided by Apache foundation. So please visit to that link and download the sever.

http://www.apache.org/dyn/closer.cgi?path=/activemq/apache-activemq/5.4.3/apache-activemq-5.4.3-bin.zip

after downloading the zip file simple extract the zip folder and after that run the activemq.bat file simply by just clicking on it.


The after clicking on it automatically server will startup.


Then open the browser simply type the URL http://localhost:8161/admin.


this is the queues and topic.




And for demo purpose we can visit the url http://localhost:8161/demo/

Program:

HelloWorldConsumer.java


package com.st.jms;

import javax.jms.Connection;

import javax.jms.Destination;

import javax.jms.Message;

import javax.jms.MessageConsumer;

import javax.jms.Session;

import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class HelloWorldConsumer {

public static void main(String[] args) {

        try {

            /* Create a ConnectionFactory*/

 ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://sanu:61616");

            /* Create a Connection*/

            Connection connection = connectionFactory.createConnection();

            connection.start();

            /* Create a Session*/

            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            /* Create the destination Topic or Queue*/

            Destination destination = session.createQueue("HELLOWORLD.TESTQ");

            /* Create a MessageConsumer from the Session to the Topic or Queue*/

            MessageConsumer consumer = session.createConsumer(destination);

            /* Wait for a message*/

            Message message = consumer.receive(1000);

            if (message instanceof TextMessage) {

                TextMessage textMessage = (TextMessage) message;

                String text = textMessage.getText();

                System.out.println("Received: " + text);

            } else {

                System.out.println("Received: " + message);

            }

            consumer.close();

            session.close();

            connection.close();

        } catch (Exception e) {

            e.printStackTrace();

        }

}

}



HelloWorldProducer.java


package com.st.jms;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class HelloWorldProducer {
public static void main(String[] args) {

        try {
            /* Create a ConnectionFactory*/
            ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://sanu:61616");
            /* Create a Connection*/
            Connection connection = connectionFactory.createConnection();
            connection.start();
            /*Create a Session*/
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            /* Create the destination Topic or Queue*/
            Destination destination = session.createQueue("HELLOWORLD.TESTQ");
            /* Create a MessageProducer from the Session to the Topic or Queue*/
            MessageProducer producer = session.createProducer(destination);
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            /* Create a messages*/
            String text = "Hello smruti! From: " + Thread.currentThread().getName();
            TextMessage message = session.createTextMessage(text);
            /* Tell the producer to send the message*/
            System.out.println("Sent message: "+ message.hashCode() + " : " + Thread.currentThread().getName());
            producer.send(message);
            /* resource deallocation*/
            session.close();
            connection.close();
        }
        catch (Exception e) {
            System.out.println("Caught: " + e);
            e.printStackTrace();
        }
   
}
}

JMSTestApp.java

package com.st.jms;

public class JMSTestApp {

public static void main(String[] args) throws Exception {

        HelloWorldProducer.main(null);

        HelloWorldConsumer.main(null);

    }

}


Output:

Sent message: 1975358023 : main

Received: Hello smruti! From: main



Just look below screen here one message is enqueued and that message also dequeued.


Example:

HelloWorldConsumer.java


package com.st.jms.thread;

import javax.jms.Connection;

import javax.jms.Destination;

import javax.jms.ExceptionListener;

import javax.jms.JMSException;

import javax.jms.Message;

import javax.jms.MessageConsumer;

import javax.jms.Session;

import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class HelloWorldConsumerThread implements Runnable, ExceptionListener {

public void run() {

        try {

            /* Create a ConnectionFactory*/

 ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://sanu:61616");

           /* Create a Connection*/

            Connection connection = connectionFactory.createConnection();

            connection.start();

            connection.setExceptionListener(this);

            /* Create a Session*/

            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            /* Create the destination (Topic or Queue)*/

            Destination destination = session.createQueue("HELLOWORLD.TESTQ");

            /* Create a MessageConsumer from the Session to the Topic or Queue*/

            MessageConsumer consumer = session.createConsumer(destination);

           /* Wait for a message*/

            Message message = consumer.receive(1000);

            if (message instanceof TextMessage) {

                TextMessage textMessage = (TextMessage) message;

                String text = textMessage.getText();

                System.out.println("Received: " + text);

            } else {

                System.out.println("Received: " + message);

            }

            consumer.close();

            session.close();

            connection.close();

        } catch (Exception e) {

            System.out.println("Caught: " + e);

            e.printStackTrace();

        }

    }

    public synchronized void onException(JMSException ex) {

        System.out.println("JMS Exception occured. Shutting down client.");

    }

}


HelloWorldProducerThread.java


package com.st.jms.thread;

import javax.jms.Connection;

import javax.jms.DeliveryMode;

import javax.jms.Destination;

import javax.jms.MessageProducer;

import javax.jms.Session;

import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class HelloWorldProducerThread implements Runnable {

public void run() {

        try {

           /* Create a ConnectionFactory*/

 ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://sanu:61616");

           /* Create a Connection*/

            Connection connection = connectionFactory.createConnection();

            connection.start();

            /* Create a Session*/

            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

           /* Create the destination (Topic or Queue)*/

            Destination destination = session.createQueue("HELLOWORLD.TESTQ");

           /* Create a MessageProducer from the Session to the Topic or Queue*/

            MessageProducer producer = session.createProducer(destination);

            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

            /* Create a messages*/

            String text = "Hello world! From: " + Thread.currentThread().getName() + " : " + this.hashCode();

            TextMessage message = session.createTextMessage(text);

            /* Tell the producer to send the message*/

System.out.println("Sent message: "+ message.hashCode() + " : " + Thread.currentThread().getName());

            producer.send(message);

         /*  Clean up logic*/

            session.close();

            connection.close();

        }

        catch (Exception e) {

            System.out.println("Caught: " + e);

            e.printStackTrace();

        }

    }

}



JMSTestAppThread.java


package com.st.jms.thread;

public class JMSTestAppThread {

public static void main(String[] args) throws Exception {

        thread(new HelloWorldProducerThread(), false);

        thread(new HelloWorldProducerThread(), false);

        thread(new HelloWorldProducerThread(), false);

        thread(new HelloWorldProducerThread(), false);

        Thread.sleep(10000);

        thread(new HelloWorldConsumerThread(), false);

        thread(new HelloWorldProducerThread(), false);

        thread(new HelloWorldConsumerThread(), false);

        thread(new HelloWorldProducerThread(), false);

        thread(new HelloWorldConsumerThread(), false);

        thread(new HelloWorldConsumerThread(), false);

        Thread.sleep(1000);

    }

    public static void thread(Runnable runnable, boolean daemon) {

        Thread newThread = new Thread(runnable);

        newThread.setDaemon(daemon);

        newThread.start();

    }

}


output:


Sent message: 1223230267 : Thread-1

Sent message: 961822459 : Thread-2

Sent message: 177798227 : Thread-3

Sent message: 680394548 : Thread-0

Sent message: 1746263845 : Thread-12

Sent message: 198811893 : Thread-14

Received: Hello world! From: Thread-12 : 2096684077

Received: Hello world! From: Thread-3 : 1192040340

Received: Hello world! From: Thread-14 : 1927609987

Received: Hello world! From: Thread-0 : 169761292


Regards

Smruti Prakash Nayak.




tags: jms

About author

User Image
smrutiprakash3824

hi this is smruti , am from odisha. I am Technically sound in Java Programming and I am very much comfortable with Web Application Development. I have good knowledge on Spring framework, Web Services, Hibernate, Restful Services, oracle, MySQL, HTML, CSS, JavaScript, spring cloud ,microservices etc

1

-Comments

Be the first person to write a comment for this Blog
  • author image
    by:
      Anjaneyalu
      12 Days ago

    nice blog. It is very easy to understand. please write some more blogs about cloud technology, micro services architectures.

Load More

No More Comments

Leave a Comment

Your comment has been posted and will appear soon.