JMS Tutorial

EJB JMS Tutorial in java with an example for beginners and professionals. The requirement of JMS, the advantage of JMS, JMS Programming Model, JMS Queue Example, Create a connection factory and destination resource, Create connection factory and destination resource, JMS Topic Example, etc.

JMS Tutorial

JMS Tutorial

JMS (Java Message Service) is an API that provides the facility to create, send and read messages. It provides loosely coupled reliable and asynchronous communication.

JMS is also known as a messaging service.


Understanding Messaging

Messaging is a technique to communicate applications or software components.

JMS is mainly used to send and receive a message from one application to another.


Requirement of JMS

Generally, the user sends the message to the application. But, if we want to send a message from one application to another, we need to use JMS API.

Consider a scenario, one application A is running in INDIA and another application B is running in the USA. To send a message from An application to B, we need to use JMS.


Advantage of JMS

1) Asynchronous: To receive the message, the client is not required to send a request. The message will arrive automatically to the client.

2) Reliable: It provides assurance that a message is delivered.


Messaging Domains

There are two types of messaging domains in JMS.

  1. Point-to-Point Messaging Domain
  2. Publisher/Subscriber Messaging Domain

1) Point-to-Point (PTP) Messaging Domain

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

The Queue is responsible to hold the message until the receiver is ready.

In the PTP model, there is no timing dependency between the sender and receiver.

 


2) Publisher/Subscriber (Pub/Sub) Messaging Domain

In the 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 the PTP model, there is timing dependency between publisher and subscriber.


JMS Queue Example

To develop a JMS queue example, you need to install any application server. Here, we are using a glassfish3 server where we are creating two JNDI.

  1. Create connection factory named myQueueConnectionFactory
  2. Create a destination resource named myQueue

After creating JNDI, create a server and receiver application. You need to run the server and receiver in the different console. Here, we are using Eclipse IDE, it is opened in the different console by default.

1) Create a connection factory and the destination resource

Open server admin console by the URL http://localhost:4848

Log in with the username and password.

Click on the JMS Resource -> Connection Factories -> New, now write the pool name and select the Resource Type as QueueConnectionFactory then clicks on ok button.

Click on the JMS Resource -> Destination Resources -> New, now write the JNDI name and physical destination name then click on ok button.

2) Create sender and receiver application

Let's see the Sender and Receiver code. Note that the Receiver is attached with the listener which will be invoked when the user sends the message.

File: MySender.java

 

  1. import java.io.BufferedReader;  
  2. import java.io.InputStreamReader;  
  3. import javax.naming.*;  
  4. import javax.jms.*;  
  5.   
  6. public class MySender {  
  7.     public static void main(String[] args) {  
  8.         try  
  9.         {   //Create and start connection  
  10.             InitialContext ctx=new InitialContext();  
  11.             QueueConnectionFactory f=(QueueConnectionFactory)ctx.lookup("myQueueConnectionFactory");  
  12.             QueueConnection con=f.createQueueConnection();  
  13.             con.start();  
  14.             //2) create queue session  
  15.             QueueSession ses=con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);  
  16.             //3) get the Queue object  
  17.             Queue t=(Queue)ctx.lookup("myQueue");  
  18.             //4)create QueueSender object         
  19.             QueueSender sender=ses.createSender(t);  
  20.             //5) create TextMessage object  
  21.             TextMessage msg=ses.createTextMessage();  
  22.               
  23.             //6) write message  
  24.             BufferedReader b=new BufferedReader(new InputStreamReader(System.in));  
  25.             while(true)  
  26.             {  
  27.                 System.out.println("Enter Msg, end to terminate:");  
  28.                 String s=b.readLine();  
  29.                 if (s.equals("end"))  
  30.                     break;  
  31.                 msg.setText(s);  
  32.                 //7) send message  
  33.                 sender.send(msg);  
  34.                 System.out.println("Message successfully sent.");  
  35.             }  
  36.             //8) connection close  
  37.             con.close();  
  38.         }catch(Exception e){System.out.println(e);}  
  39.     }  
  40. }  

File: MyReceiver.java

 

  1. import javax.jms.*;  
  2. import javax.naming.InitialContext;  
  3.   
  4. public class MyReceiver {  
  5.     public static void main(String[] args) {  
  6.         try{  
  7.             //1) Create and start connection  
  8.             InitialContext ctx=new InitialContext();  
  9.             QueueConnectionFactory f=(QueueConnectionFactory)ctx.lookup("myQueueConnectionFactory");  
  10.             QueueConnection con=f.createQueueConnection();  
  11.             con.start();  
  12.             //2) create Queue session  
  13.             QueueSession ses=con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);  
  14.             //3) get the Queue object  
  15.             Queue t=(Queue)ctx.lookup("myQueue");  
  16.             //4)create QueueReceiver  
  17.             QueueReceiver receiver=ses.createReceiver(t);  
  18.               
  19.             //5) create listener object  
  20.             MyListener listener=new MyListener();  
  21.               
  22.             //6) register the listener object with receiver  
  23.             receiver.setMessageListener(listener);  
  24.               
  25.             System.out.println("Receiver1 is ready, waiting for messages...");  
  26.             System.out.println("press Ctrl+c to shutdown...");  
  27.             while(true){                  
  28.                 Thread.sleep(1000);  
  29.             }  
  30.         }catch(Exception e){System.out.println(e);}  
  31.     }  
  32.   
  33. }  

File: MyListener.java

 

  1. import javax.jms.*;  
  2. public class MyListener implements MessageListener {  
  3.   
  4.     public void onMessage(Message m) {  
  5.         try{  
  6.         TextMessage msg=(TextMessage)m;  
  7.       
  8.         System.out.println("following message is received:"+msg.getText());  
  9.         }catch(JMSException e){System.out.println(e);}  
  10.     }  
  11. }  

Run the Receiver class first then Sender class.


JMS Topic Example

It is the same as JMS Queue, but you need to change Queue to Topic, Sender to Publisher and Receiver to Subscriber.

You need to create 2 JNDI named myTopicConnectionFactory and myTopic.

File: MySender.java

 

  1. import java.io.BufferedReader;  
  2. import java.io.InputStreamReader;  
  3. import javax.naming.*;  
  4. import javax.jms.*;  
  5.   
  6. public class MySender {  
  7.     public static void main(String[] args) {  
  8.         try  
  9.         {   //Create and start connection  
  10.             InitialContext ctx=new InitialContext();  
  11.             TopicConnectionFactory f=(TopicConnectionFactory)ctx.lookup("myTopicConnectionFactory");  
  12.             TopicConnection con=f.createTopicConnection();  
  13.             con.start();  
  14.             //2) create queue session  
  15.             TopicSession ses=con.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);  
  16.             //3) get the Topic object  
  17.             Topic t=(Topic)ctx.lookup("myTopic");  
  18.             //4)create TopicPublisher object          
  19.             TopicPublisher publisher=ses.createPublisher(t);  
  20.             //5) create TextMessage object  
  21.             TextMessage msg=ses.createTextMessage();  
  22.               
  23.             //6) write message  
  24.             BufferedReader b=new BufferedReader(new InputStreamReader(System.in));  
  25.             while(true)  
  26.             {  
  27.                 System.out.println("Enter Msg, end to terminate:");  
  28.                 String s=b.readLine();  
  29.                 if (s.equals("end"))  
  30.                     break;  
  31.                 msg.setText(s);  
  32.                 //7) send message  
  33.                 publisher.publish(msg);  
  34.                 System.out.println("Message successfully sent.");  
  35.             }  
  36.             //8) connection close  
  37.             con.close();  
  38.         }catch(Exception e){System.out.println(e);}  
  39.     }  
  40.  

File: MyReceiver.java

 

  1. import javax.jms.*;  
  2. import javax.naming.InitialContext;  
  3.   
  4. public class MyReceiver {  
  5.     public static void main(String[] args) {  
  6.         try {  
  7.             //1) Create and start connection  
  8.             InitialContext ctx=new InitialContext();  
  9.             TopicConnectionFactory f=(TopicConnectionFactory)ctx.lookup("myTopicConnectionFactory");  
  10.             TopicConnection con=f.createTopicConnection();  
  11.             con.start();  
  12.             //2) create topic session  
  13.             TopicSession ses=con.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);  
  14.             //3) get the Topic object  
  15.             Topic t=(Topic)ctx.lookup("myTopic");  
  16.             //4)create TopicSubscriber  
  17.             TopicSubscriber receiver=ses.createSubscriber(t);  
  18.               
  19.             //5) create listener object  
  20.             MyListener listener=new MyListener();  
  21.               
  22.             //6) register the listener object with subscriber  
  23.             receiver.setMessageListener(listener);  
  24.                           
  25.             System.out.println("Subscriber1 is ready, waiting for messages...");  
  26.             System.out.println("press Ctrl+c to shutdown...");  
  27.             while(true){                  
  28.                 Thread.sleep(1000);  
  29.             }  
  30.         }catch(Exception e){System.out.println(e);}  
  31.     }  
  32. }  

File: MyListener.java

 

  1. import javax.jms.*;  
  2. public class MyListener implements MessageListener {  
  3.   
  4.     public void onMessage(Message m) {  
  5.         try{  
  6.         TextMessage msg=(TextMessage)m;  
  7.       
  8.         System.out.println("following message is received:"+msg.getText());  
  9.         }catch(JMSException e){System.out.println(e);}  
  10.     }  
  11. }