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:

MOM vs ESB


MOM - Message Oriented Middleware
ESB - Enterprise Service BUS



I consider MOM a building block for ESB solutions. In fact, ESB solutions reach their own loose coupling and asynchronous communication capabilities, just using the paradigm offered by the specific MOM implementation.
Therefore, MOMs represent solutions for data/events distribution at customized level of QoSs (according to the specific vendor implementation), instead ESBs represent solutions providing capabilities to realize complex orchestrations in a SOA scenario (where we have multiple providers offering their services, and multiple consumers interested in consuming the services offered by the first ones).

Complex orchestrations imply communication between legacy systems, everyone of these with its own data domain representation (rules and services on specific data) and its own communication paradigm (one consumer interact with the ESB using CORBA, another one using WS, and so on).
It is clear that ESB represents a more complex architectural solution aimed to provide the abstraction of data-bus (such as the electronic buses that everyone have in his own pc), able to connect a plethora of service providers to a not well specified plethora of service consumers, hiding heterogeneity in (i) data representation and (ii) communication.


ESB is just yet another buzzword, as is SOA 2.0.
You can have a ESB system easily implemented with normal Web Services with a queue behind them. You can have message routing and or orchestration with SOA 1.0 (Tibco{EMS}, BizzTalk), one things does not stop the other really. More importantly, it is the semantics given to the messages exchanged in the system that play an important role, in this case events. Messages as events, are triggers about something that happened in your system, so the context is different.


ESB:













 MOM :






MessageQueue vs Message Broker


MQ is a solution for application-to-application communication services regardless of where your applications or data reside. Whether on a single server, separate servers of the same type, or separate servers of different architecture types, MQ facilitates communications between applications by sending and receiving message data via messaging queues. Applications then use the information in these messages to interact with Web browsers, business logic, and databases. MQ provides a secure and reliable transport layer for moving data unchanged in the form of messages between applications but it is not aware of the content of the messages. MQ uses a set of small and standard application programming interfaces (APIs) that support a number of programming languages, including Visual Basic, NATURAL, COBOL, Java, and C across all platforms.

Message Broker is built to extend MQ, and it is capable of understanding the content of each message that it moves through the Broker. Customers can define the set of operations on each message depending on its content. The message processing nodes supplied with Message Broker are capable of processing messages from various sources, such as Java Message Service (JMS) providers, HyperText Transfer Protocol (HTTP) calls, or data read from files. By connecting these nodes with each other, customers can define linked operations on a message as it flows from one application to its destination.
Message Broker can do the following:
    * Matches and routes communications between services
    * Converts between different transport protocols
    * Transforms message formats between requestor and service
    * Identifies and distributes business events from disparate sources
Together, MQ and Message Broker deliver a comprehensive publish and subscribe facility, connecting Message Broker’s broad transport and format support to MQ’s messaging backbone. Message Broker extends the MQ publish and subscribe functionality with advanced function such as content-based publish and subscribe by means of an enhanced Publication node. The two products share a common publish and subscribe domain for topic- and content-based operations

Java Perspective :
===============

Message Broker - The message-oriented middleware server that hosts messaging destinations (i.e., queues and topics) for the purposes of asynchronous communication. Sometimes known as a queue manager
Message Queue - A messaging destination that uses a queue data structure to hold messages and is hosted by the message broker. The alternative to a queue is a topic which provides publish/subscribe semantics.
Resource Adapter - A Java EE Resource Adapter is a component that allows communication between a Java EE application and an enterprise information system such as a database server, a messaging server, a CRM server, an ERP server, etc.