JMS

How to Implement JMS with Tomcat – Durable Subscription Example

Posted on Updated on

java-logoIn this A Durable Subscription Example, we will see how to implement JMS with Tomcat.  read What is JMS in previous article.

Tomcat doesn’t supports JMS itself but using some external library ( ActiveMQ ) we can accomplish it. here we use JMS vendor – ActiveMQ

so, before getting started, download couple of libraries and put it into Tocat/lib directory and Project classpath.

or Copy and paste below Maven Dependencies in your pom.xml file:-

 <dependency>
 <groupId>commons-logging</groupId>
 <artifactId>commons-logging</artifactId>
 <version>1.2</version>
 </dependency>
 <dependency>
 <groupId>org.apache.activemq</groupId>
 <artifactId>activemq-all</artifactId>
 <version>5.11.1</version>
 </dependency>

Next, add the resource below to conf/server.xml:

<GlobalNamingResources>
 <Resource name="ConnectionFactory" auth="Container"
 type="org.apache.activemq.ActiveMQConnectionFactory" description="JMS
 Connection Factory " factory="org.apache.activemq.jndi.JNDIReferenceFactory"
 brokerurl="tcp://localhost:61617"
 brokerName="ActiveMQBroker"
 useEmbeddedBroker="false"/>

 <Resource name="jms/topic/ITExpertsTopic" auth="Container"
 type="org.apache.activemq.command.ActiveMQTopic" factory="org.apache.activemq.jndi.JNDIReferenceFactory"
 physicalName="APP.JMS.TOPIC" />

 <Resource name="jms/queue/ITExpertsQueue" auth="Container"
 type="org.apache.activemq.command.ActiveMQQueue" factory="org.apache.activemq.jndi.JNDIReferenceFactory"
 physicalName=" APP.JMS.QUEUE" />

 </GlobalNamingResources>

Next, add this code to context.xml:

<ResourceLink global="jms/ConnectionFactory" name="jms/ConnectionFactory" type="javax.jms.ConnectionFactory"/>
<ResourceLink global="jms/topic/ITExpertsTopic" name="jms/topic/ITExpertsTopic" type="javax.jms.Topic"/>
<ResourceLink global="jms/queue/ITExpertsQueue" name="jms/queue/ITExpertsQueue" type="javax.jms.Queue"/>

Next, We need to add ActiveMQ props into tomcat class path:

set JAVA_OPTS=-Dwebconsole.type=properties -Dwebconsole.jms.url=”tcp://localhost:61617″ -Dwebconsole.jmx.url=”service:jmx:rmi:///jndi/rmi://localhost:1099/ jmxrmi”

Below are code snippet of A Durable Subscription Example :-

MessageProducerClient.Java

package com.itexperts.jms;
/**
 * 
 * @author #Ajay
 *
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.activemq.broker.BrokerService;

public class MessageProducerClient {

 public static Properties getProp() {
 Properties props = new Properties();
 props.setProperty(Context.INITIAL_CONTEXT_FACTORY,
 "org.apache.activemq.jndi.ActiveMQInitialContextFactory");
 props.setProperty(Context.PROVIDER_URL, "tcp://localhost:61617");
 return props;
 }

 public static void initBroker() throws Exception {
 BrokerService broker = new BrokerService();
 // configure the broker
 broker.addConnector("tcp://localhost:61617");
 broker.start();
 }

 public static void main(String args[]) {

 Connection connection = null;
 try {
 initBroker();
 InitialContext jndiContext = new InitialContext(getProp());
 ConnectionFactory connectionFactory = (ConnectionFactory) jndiContext
 .lookup("ConnectionFactory");
 connection = connectionFactory.createConnection();
 connection.setClientID("durable");
 Session session = connection.createSession(false,
 Session.AUTO_ACKNOWLEDGE);
 Destination destination = session
 .createTopic("jms/topic/ITExpertsTopic");
 MessageProducer producer = session.createProducer(destination);
 TextMessage msg = session.createTextMessage();
 msg.setText("Hello, This is JMS example !!");
 BufferedReader reader = new BufferedReader(new InputStreamReader(
 System.in));
 while (true) {
 System.out
 .println("Enter Message to Topic or Press 'Q' for Close this Session");
 String input = reader.readLine();
 if ("Q".equalsIgnoreCase(input.trim())) {
 break;
 }
 msg.setText(input);
 producer.send(msg);
 }
 } catch (JMSException e) {
 e.printStackTrace();
 } catch (IOException e) {
 e.printStackTrace();
 } catch (NamingException e) {
 e.printStackTrace();
 } catch (Exception e) {
 e.printStackTrace();
 } finally {
 try {
 if (connection != null) {
 connection.close();
 }
 } catch (JMSException e) {
 e.printStackTrace();
 }
 }

 }
}

MessageReceiverClient.Java


package com.itexperts.jms;

import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;

import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 
 * @author #Ajay
 *
 */
public class MessageReceiverClient {
 protected static final String url = "tcp://localhost:61617";

 public static void main(String args[]) {

 TopicConnection connection = null;
 try {
 ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(
 url);
 connection = factory.createTopicConnection();
 connection.setClientID("durable");
 connection.start();
 MessageConsumer consumer = null;
 Session session = connection.createTopicSession(false,
 Session.AUTO_ACKNOWLEDGE);
 Topic topic = session.createTopic("jms/topic/ITExpertsTopic");
 consumer = session.createDurableSubscriber(topic, "mySub");
 // consumer.setMessageListener(new ReceiverListener());

 // System.out.println(" Waiting for Message ...");
 // while(true){
 // Thread.sleep(1000);
 // }
 while (true) {
 TextMessage message = (TextMessage) consumer.receive();
 System.out.println(message.getText());
 }
 } catch (Exception e) {
 e.printStackTrace();
 } finally {
 try {
 if (connection != null) {
 connection.close();
 }
 } catch (JMSException e) {
 e.printStackTrace();
 }
 }

 }

}

Compile and run these two Java files separately in two command prompt.

Here you will see how durable topics works when a Sender/Producer send a bunch of messages while  Subscriber/ Receiver is not yet active.

Step 1: Compile and run MessageProducerClient.Java file. Send some message to durable using command prompt.

Step 2: Compile and run MessageReceiverClient.Java file. When you run this file then all messages that are retain on Destination Durable Topic get started consuming and print on console.

 

Advertisements

What is JMS – Java Message Service

Posted on Updated on

java-logoIn this tutorial, we will see the overview of JMS and it’s implementations. JMS was developed by Sun Microsystems that allows a Java programming language to communicate with other messaging systems. Mostly JMS enables in distributed application where two or more Software Components or Applications pointing to same Destination( i.e Queue/Topic/Durable) in the way to communicating to each other by sending or reading the message subsequently.

Suppose, A component sends a message to a destination, and the recipient can retrieve the message from the destination. However, the sender and the receiver do not have to be available at the same time in order to communicate. In fact, the sender does not need to know anything about the receiver; nor does the receiver need to know anything about the sender. The sender and the receiver need to know only which message format and which destination to use. In this respect, Durable Topic can be helpful which retains the messages while the Subscriber is not active. Once the Subscribers get activated then messages can be received from durable.

What is JMS?

Java message service enables loosely coupled communication between two or more systems. It provides reliable and asynchronous form of communication. There are two types of messaging models in JMS.

Point-to-Point Messaging Domain

Applications are built on the concept of message queues, senders, and receivers. Each message is send to a specific queue, and receiving systems consume messages from the queues established to hold their messages. Queues retain all messages sent to them until the messages are consumed by the receiver or expire. Here there is only one consumer for a message. If the receiver is not available at any point, message will remain in the message broker (Queue) and will be delivered to the consumer when it is available or free to process the message. Also receiver acknowledges the consumption on each message.

Publish/Subscribe Messaging Domain

Applications send message to a message broker called Topic. This topic publishes the message to all the subscribers. Topic retains the messages until it is delivered to the systems at the receiving end. Applications are loosely coupled and do not need to be on the same server. Message communications are handled by the message broker; in this case it is called a topic. A message can have multiple consumers and consumers will get the messages only after it gets subscribed and consumers need to remain active in order to get new messages.

 

Message can be consumed either two ways:-

  • Synchronously: A subscriber or a receiver explicitly fetches the message from the destination by calling the receive method. The receive method can block until a message arrives or can time out if a message does not arrive within a specified time limit.
  • Asynchronously: A client can register a message listener with a consumer. A message listener is similar to an event listener. Whenever a message arrives at the destination, the JMS provider delivers the message by calling the listener’s onMessage method, which acts on the contents of the message.

Building Block of JMS Application are:-

The JMS API Programming Model

Diagram of the JMS API programming model: connection factory, connection, session, message producer, message consumer, messages, and destinations

First we need to create a connection object using the ActiveMQConnectionFactory factory object. Then we create a session object.  Using the session object we set the message broker (Queue) and create the message sender object.

Below are some JMS Implementation in JAVA:-