In perivous article, we have read about basics of messaging system and come to know that how messaging can help in quite flexible and abstract integration of various software applications. Now let us move further towards basics of Java Message Service (JMS), which can help us to implement the messaging concepts read till now.
JMS is a Messaging Oriented Middleware. Middleware is the software used to connect more than one software applications (distributed also) in quite flexible manner. Middleware can be of two typs, RPC based and messaging based. RPC based Middleware is one which provided synchronous integration between two software applications. Whereas, Messaging based Middleware (MOM) is one which inetgrate two software applications asynchronously using messaging concept. Certainly nowadays, MOM are quite popular where client can not wait for response from service and hence want a asynchronous request processing. JMS comes in this category. JMS can also be used for synchronous communication with some efforts, however, that is not something for which JMS comes in existence. It is devised specially to strengthen and standardize the messaging oriented middleware software.
Before JMS, there were many messaging solutions in market from various Industry players, like from IBM, Progress Software and Fiorano etc. Problem was, these products were not following any standard specification. So suppose, today you find that Software A is meeting your requirement and use it for implementation. After one year, you met with some new requirements, and then found that A can not meet these requirements but B has these new features. But, now it was not easy to replace the messaging software due to lack of any standard API implementation. JMS has solved this problem by defining a standard to implement the messaging systems with an abstract API. Now, clients can easily switch from one to other vendor anytime as per requirement without disturbing the implementation of application.
Hence JMS is a specification which defines an API allowing java based applications to utilize the features of any JMS compliant MOM software, without sticking to any one implementation. It provides a right level of abstraction from proprietary implementation of MOM systems. JMS is not an actual product. Actual products are still coming from indepdent software product companies like IBM, Progress Software etc. However, now, these products are adhering to the protocol defined by JMS specification, and hence following a standard approach with many of their specific advance features like load balancing, persistence, fault tolerance and administration etc. JMS is also implemented in J2EE in form of Message Driven Beans. Hence it becomes a intrinsic part of J2EE specification now.
As we have understood in previous article, that messaging can be of two types which are Point to Point messaging and Publisher/Subscriber messaging. JMS supports both of these messaging style. However, it is not mandatory for implementing products to support both of these styles. These products are still JMS compliant, even, if they are supporting only one messaging style. So JMS have defined different domain and API for each of these messaging style.
Now let us understand the main API components of JMS. Main components are:
- Connection - It is a kind of logical connection from client to JMS provider, which create a link between JMS provider and the client applications.
- Connection Factory - It is a factory to get the connection with JMS Provider.
- Session - It is like a private domain within a connection. One connection can have more than one sessions, and every session will have its own separate work area. So one connection can have more than one sessions at a time, and each session may be sending different messages. Session itself can not be used for sending or receiving the messages. Instead, session is like a factory object to create message producer or consumer which actually send or receive the messages.
- Destination - Destination is like a message broker, where every message needs to be delivered and from where every message will be received. Destination for point to point is called 'Queue' and for publish/subscribe, it is called 'Topic'.
- Message Producer - The component which will produce the message in the system
- Message Consumer - The component which will receive/consume the message in the system
Here is a sample code for using Oracle/Sun messaging system. This may give you an overview of implementation before moving forward with more details.
Sample Code for Point to Point messaging style-
// The Point to Point Sender Program: P2PMessageSender.java
import javax.jms.*;
public class P2PMessageSender {
public static void main(String[] args) throws Exception
{
try {
// initialization
// Get connection factory with point-to-point style (queue connection factory)
QueueConnectionFactory myConnectionFactory =
new com.sun.messaging.QueueConnectionFactory();
// Get queue connection
QueueConnection myConnection = myConnectionFactory.createQueueConnection();
// Create queue session
QueueSession mySession = myConnection.createQueueSession(false,1);
// Get the queue
Queue myQueue = mySession.createQueue("MyP2PQueue");
// Create a sender
QueueSender mySender = mySession.createSender(myQueue);
// Start the connection
myConnection.start();
// Create the message
TextMessage m = mySession.createTextMessage();
m.setText("My first P2P message");
// Send the message
mySender.send(m);
// Release the resources
mySession.close();
myConnection.close();
}
catch( Exception e ) {
// Handle Exception
e.printStackTrace();
}
}
}
// The Point to Point Receiver Program: P2PMessageReceiver.java
import javax.jms.*;
public class P2PMessageReceiver {
public static void main(String[] args) throws Exception
{
try {
// initialization
// Get connection factory with point-to-point style (queue connection factory)
QueueConnectionFactory myConnectionFactory =
new com.sun.messaging.QueueConnectionFactory();
// Get queue connection
QueueConnection myConnection = myConnectionFactory.createQueueConnection();
// Create queue session
QueueSession mySession = myConnection.createQueueSession(false,1);
// Get the queue
Queue myQueue = mySession.createQueue("MyP2PQueue");
// Create a receiver
QueueReceiver myReceiver = mySession.createReceiver(myQueue);
// Start the connection
myConnection.start();
// Wait for message
// Following call will wait forever for the message
TextMessage message = (TextMessage)myReceiver.receive();
System.out.println("message: " + message.getText());
// release the resources
mySession.close();
myConnection.close();
}
catch( Exception e ) {
// handle exception properly
e.printStackTrace();
}
}
}
Sample Code for Publish/Subscribe messaging style-
// The Point to Point Sender Program: PSMessageSender.java
import javax.jms.*;
public class PSMessageSender {
public static void main(String[] args) throws Exception
{
try {
// initialization
// Get connection factory with Publisher/Subscriber style (queue connection factory)
TopicConnectionFactory myConnectionFactory =
new com.sun.messaging.TopicConnectionFactory();
// Get Topic connection
TopicConnection myConnection = myConnectionFactory.createTopicConnection();
// Create topic session
TopicSession mySession = myConnection.createTopicSession(false,1);
// Get the topic
Topic myTopic = mySession.createTopic("MyPSTopic");
// Create a sender
TopicPublisher myPublisher = mySession.createPublisher(myTopic);
// Start the connection
myConnection.start();
// Create the message
TextMessage m = mySession.createTextMessage();
m.setText("My first PS message");
// Send the message
myPublisher.send(m);
// Release the resources
mySession.close();
myConnection.close();
}
catch( Exception e ) {
// Handle Exception
e.printStackTrace();
}
}
}
// The Point to Point Receiver Program: P2PMessageReceiver.java
import javax.jms.*;
public class P2PMessageReceiver {
public static void main(String[] args) throws Exception
{
try {
// initialization
// Get connection factory with Publisher/Subscriber style (queue connection factory)
TopicConnectionFactory myConnectionFactory =
new com.sun.messaging.TopicConnectionFactory();
// Get Topic connection
TopicConnection myConnection = myConnectionFactory.createTopicConnection();
// Create topic session
TopicSession mySession = myConnection.createTopicSession(false,1);
// Get the topic
Topic myTopic = mySession.createTopic("MyPSTopic");
// Create a Subscriber
TopicSubscriber mySubscriber = mySession.createSubscriber(myTopic);
// Start the connection
myConnection.start();
// Wait for message
// Following call will wait forever for the message
TextMessage message = (TextMessage)mySubscriber.receive();
System.out.println("message: " + message.getText());
// release the resources
mySession.close();
myConnection.close();
}
catch( Exception e ) {
// handle exception properly
e.printStackTrace();
}
}
}
Now to run these sample code, you should have Sun Messaging System on your system. After that, set the environment variables like JMQ_HOME to the home directory of JMS system and add JMS lib directory jars to classpath. Now follow the steps given below:
Start JMS router by running 'irouter' class
Run P2PMessageReceiver
Run P2PMessageSender
Message should be printed on the screen, as receiver is printing the received message. If you will try to run more than one P2PMessageReceiver simultaneously, system will given you an error saying that more than one receiver can not be run at a time. It is because, we are running a Point to Point system, where only one receiver can exist.
Run PSMessageReceiver
RunPSMessageSender
Message should be printed on the screen, as receiver is printing the received message. Here, if you want, you can run multiple message receiver simultaneously. All of those receivers should get the message and print these. It is because, we are using Publish/Subscribe messaging style and hence subcriber can be more than one.
This way, you can try with very simple examples of JMS.
This is a brief article on basics of JMS API. Here, we learned about what is JMS, its various important components and about a very basic example. It should help to create a basic understanding about JMS. In coming article, we shall discuss about JMS API in more depth, with few more advance features. Keep in tune with next articles by subscribing to our emails or by liking the website page on Facebook.
0 comments:
Post a Comment