Tuesday 26 August 2014

JMS Overview



History:
Before JMS defined by JAVA SUN , there are different specific clients provided by  MQ  . In order to make it more generalize the interaction with QUEUES from java application, SUN introduced/defined JMS API  Interface Specification. In which most of well known QUEUES implemented the JMS API.


What is JMS ?

JMS  is uniform API provided by Java platform which enables developer to work directly with JMS API and need not to worry what is underlying messaging framework. A messaging implementation has to be JMS-compliant in order to be worked upon by JMS APIs.

The Java Message Service (JMS) API is a Java Message Oriented Middleware (MOM) API  for sending messages between two or more clients. JMS is a part of the Java Platform, Enterprise Edition, and is defined by a specification developed under the Java Community Process as JSR 914. It is a messaging standard that allows application components based on the Java Enterprise Edition (Java EE) to create, send, receive, and read messages. It allows the communication between different components of a distributed application to be loosely coupled, reliable, and asynchronous.


JMS Analogy

JMS interface API is similar with analogy of JDBC interface API, in case of JDBC we have different databases in JMS case we have different queues.

Most of the application servers like WEBLOGIC, GLASSFISH,JBOSS,WEBSPHERE have their own Queues inside the server.

Example:
Lets talk about the  example of the Glassfish server, it have OPEN MQ  and JMS implemented . So we can directly access OPEN MS from Glassfish server using JMS. We can also integrate the third party Queues like ACTIVE-MQ   into GLASSFISH server using Resource Adapter module of Glassfish .

Note:
JMS is one of the option for accessing the queues. We also have other options like QUEUE specific client jar and Spring supported jar.




What is JMS used for ?

It is used to access queues in Application servers . Most of the application servers have their own queue s  available with server.
  1. Websphere - IBM MQ
  2. GlassFish- Open MQ
  3. Jboss - Jboss MQ

Most widely/known  MQ is ActiveMQ( built on Java), IBM MQ, MS MQ.


JMS Elements/Terminology :

JMS provider
An implementation of the JMS interface for a Message Oriented Middleware (MOM). Providers are implemented as either a Java JMS implementation or an adapter to a non-Java MOM.
JMS client
An application or process that produces and/or receives messages.
JMS producer/publisher
A JMS client that creates and sends messages.
JMS consumer/subscriber
A JMS client that receives messages.
JMS message
An object that contains the data being transferred between JMS clients.
JMS queue
A staging area that contains messages that have been sent and are waiting to be read (by only one consumer). Note that, contrary to what the name queue suggests, messages don't have to be delivered in the order sent. A JMS queue only guarantees that each message is processed only once.
JMS topic
A distribution mechanism for publishing messages that are delivered to multiple subscribers.


What are JMS Models ?

Models
The JMS API supports two models:
  • Point-to-point
  • Publish and subscribe

Point-to-point model
In point-to-point messaging system, messages are routed to an individual consumer which maintains a queue of "incoming" messages. This messaging type is built on the concept of message queues, senders, and receivers. Each message is addressed to a specific queue, and the receiving clients extract messages from the queues established to hold their messages. While any number of producers can send messages to the queue, each message is guaranteed to be delivered, and consumed by one consumer. Queues retain all messages sent to them until the messages are consumed or until the messages expire. If no consumers are registered to consume the messages, the queue holds them until a consumer registers to consume them.

Publish/subscribe model
The publish/subscribe model supports publishing messages to a particular message topic. Subscribers may register interest in receiving messages on a particular message topic. In this model, neither the publisher nor the subscriber knows about each other. A good analogy for this is an anonymous bulletin board.
  • Zero or more consumers will receive the message.
  • There is a timing dependency between publishers and subscribers. The publisher has to create a message topic for clients to subscribe. The subscriber has to remain continuously active to receive messages, unless it has established a durable subscription. In that case, messages published while the subscriber is not connected will be redistributed whenever it reconnects.
JMS provides a way of separating the application from the transport layer of providing data. The same Java classes can be used to communicate with different JMS providers by using the Java Naming and Directory Interface (JNDI) information for the desired provider. The classes first use a connection factory to connect to the queue or topic, and then use populate and send or publish the messages. On the receiving side, the clients then receive or subscribe to the messages.




Its an overview of the JMS API programming model.

Code Explanation:

  1. First create the Destination (Queue) in Application Server ( GlassFish).
  1. Create Connection Factory for that Queue to access from JMS API.
  1. With these two steps GlassFish server will be used for Queue connection management.
  2. Create the MDB (Message Driven Bean ) in Enterprise Application(EJB ear file).
  3. This MDB will act as Consumer Bean to access and consume/receive message from Queue.
  4. Here we used session beans for Producer bean in EJB to produce messages to Queue.




Sending Message:
ConnectionFactory>Connection>Session>MessageProducer>send



Message Producer in EJB Session Bean:

Receive Message:
ConnectionFactory>Connection>Session>Message Consumer>receive
Listener Implementation model.

-------------------------------------------------
package sessionbeans;

import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.jms.JMSConnectionFactory;
import javax.jms.JMSContext;
import javax.jms.Queue;

/**
 * Message Producer Session Bean
 * @author Kumar
 */
@Stateless
public class ProducerSB implements ProducerSBLocal
{
    @Resource(mappedName = "jms/kumarqueue")
    private Queue kumarqueue;
    @Inject
    @JMSConnectionFactory("jms/kumarQConFactory")
    private JMSContext context;

    private void sendJMSMessageToKumarqueue(String messageData) {
        context.createProducer().send(kumarqueue, messageData);
    }
   
   
   
    public void sendMessageToQueue(String message)
    {
        sendJMSMessageToKumarqueue(message);
    }

  
}


Message Consumer in EJB-3.0 Message Driven Bean

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package messagedrivenbeans;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

/**
 *
 * @author Kumar
 */
@MessageDriven(activationConfig = {
    @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
    @ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = "jms/kumarqueue")
})
public class ConsumerMessageDrivenBean implements MessageListener {
   
    public ConsumerMessageDrivenBean() {
    }
   
    @Override
    public void onMessage(Message message)
    {
        TextMessage textMessage = (TextMessage)message;
       
        for (int i = 0; i < 10; i++)
        {
            try {
                System.out.println(i + ":" + textMessage.getText());
                Thread.sleep(1000);
            } catch (JMSException ex) {
                Logger.getLogger(ConsumerMessageDrivenBean.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InterruptedException ex) {
                Logger.getLogger(ConsumerMessageDrivenBean.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
       
    }
   
}//End of Class


JMS Advantages :

JMS is asynchronous in nature. Thus not all the pieces need to be up all the time for the application to function as a whole. Even if the receiver is down the MOM will store the messages on it's behalf and will send them once it comes back up. Thus at least a part of application can still function as there is no blocking.

What are different type of messages supported in JMS API ?
Message, TextMessage, BytesMessage, StreamMessage, ObjectMessage, MapMessage are the different messages available in the JMS API

Where to use ?
JMS is typically used in the following scenarios
1. Enterprise Application Integration: - Where a legacy application is integrated with a new application via messaging.
2. B2B or Business to Business: - Businesses can interact with each other via messaging because JMS allows organizations to cooperate without tightly coupling their business systems.
3. Geographically dispersed units: - JMS can ensure safe exchange of data amongst the geographically dispersed units of an organization.
4. One to many applications: - The applications that need to push data in packet to huge number of clients in a one-to-many fashion are good candidates for the use JMS. Typical such applications are Auction Sites, Stock Quote Services etc.


How to Implement JMS  in different Technologies ?

We have different approaches for accessing queues using JMS .
  1. Spring Integration approach
  1. EJB - Message Driven Bean Approach



Resources:

No comments:

Post a Comment

Please comment here