StackStalk
  • Home
  • Java
    • Java Collection
    • Spring Boot Collection
  • Python
    • Python Collection
  • C++
    • C++ Collection
    • Progamming Problems
    • Algorithms
    • Data Structures
    • Design Patterns
  • General
    • Tips and Tricks

Saturday, October 18, 2014

Java Messaging Service (JMS) using ActiveMQ

 October 18, 2014     Java     No comments   

This article provides an introduction to Java Messaging Service (JMS) and explains producer and consumer with simple examples.

Java Messaging Service (JMS) Introduction

Java Messaging Service (JMS) provides a mechanism for applications to create, send and receive messages using reliable, asynchronous and loosely coupled communication. JMS is defined as part of the Java Enterprise Edition.

JMS supports two messaging models, point-to-point model and the publish subscribe model. In the point to point messaging model we have a message queue and there is one consumer for the messages, but there could be multiple producers writing to the message queue. The publish subscribe message model is more like a bulletin board where there could be multiple consumers for a message. JMS client address messages to a Topic.

Some of the common terminology used with JMS applications is listed below.

  1. JMS Provider The underlying messaging system that implements the JMS APIs and supports the administrative and control features. ActiveMQ is a JMS Provider.
  2. JMS Client An application that produces or consumes messages.
  3. Message Objects used for communication between JMS clients.
  4. Administrative Objects Preconfigured objects like connection factories and destinations that are created by an administrator and used by clients.

ActiveMQ Introduction and Configuration

ApacheMQ is a popular and powerful open source messaging provider and fully supports the JMS API specifications. There are several other JMS providers including Oracle Weblogic, WebSphere MQ from IBM, OpenJMS to name a few. For the purpose of this tutorial we will use ActiveMQ as the JMS provider.

Installation and configuration of ActiveMQ is pretty simple.

  1. Download binary release for the specific platform from this link http://activemq.apache.org/.
  2. Unzip the downloaded file to a specific folder.
  3. Start ActiveMQ using the below command on a terminal window.
  4. C:\Installs\ApacheMQ\bin\activemq start
      
  5. Test if ApacheMQ is running correctly by checking if it is listening on port 61616.
  6.   C:\Users\dummy>netstat -an | find "61616"
      TCP    0.0.0.0:61616    0.0.0.0:0     LISTENING
      TCP    [::]:61616       [::]:0        LISTENING
      
  7. ApacheMQ can be monitored through the Web Console using this url http://localhost:8161/admin. Username and password is admin/ admin.

JMS Producer Example

In the JMS Producer application we use a ActiveMQ connection factory object to create a Connection to the underlying messaging system. Then we create a context for sending messages using the Session object. Then we create a Topic instance to get publish and subscribe behaviour. MessageProducer is used for sending messages. Note. Include "activemq-all-5.10.0.jar" available in the ActiveMQ installation directory as an external jar to the JMS Producer project.
import javax.jms.*;

import org.apache.activemq.ActiveMQConnectionFactory;

public class PublisherMain {
  
  public static void main (String[] args) {

    ConnectionFactory connectionFactory = null;
    Connection connection = null;
    
    try {     
      // Get a connection for sending messages
      connectionFactory = new ActiveMQConnectionFactory();
      connection = connectionFactory.createConnection();
      connection.start();
      
      // Create a session
      Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
      
      // Create a topic and send messages
      Topic topic = session.createTopic("test1");
      MessageProducer producer = session.createProducer(topic);
      while ( true ) {
        TextMessage message = session.createTextMessage();
        message.setText("This is a test JMS Message");
        producer.send(message);
        Thread.sleep(10000);
      }
    } catch (JMSException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    finally {
      try {
        connection.close();
      } catch (JMSException e) {
        e.printStackTrace();
      }
    }
  }
}

JMS Consumer Example

In the JMS Producer application we use a ActiveMQ connection factory object to create a Connection to the underlying messaging system. Then we create a Session context and subscribe to the topic. MessageConsumer is used for receiving messages. Note. Include "activemq-all-5.10.0.jar" available in the ActiveMQ installation directory as an external jar to the JMS Consumer project.
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Message;
import javax.jms.Topic;
import org.apache.activemq.ActiveMQConnectionFactory;

public class ListenerMain {
  
  public static void main(String[] args) {
    ConnectionFactory connectionFactory = null;
    Connection connection = null;
    try {
      // Get a connection for receiving messages    
      connectionFactory = new ActiveMQConnectionFactory();
      connection = connectionFactory.createConnection();
      connection.start();
      
      // Create a session
      Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
      
      // Create a topic and subscribe
      Topic topic = session.createTopic("test1");       
      MessageConsumer consumer = session.createConsumer(topic);
          
      // Receive the messages and print
      while ( true ) {
        Message message = consumer.receive();
        
        if (message instanceof TextMessage) {
              TextMessage textMessage = (TextMessage) message;
              System.out.println("Received message: "
                      + textMessage.getText());
        }
      }
    } catch (JMSException e) {
      e.printStackTrace();
    }
    finally {
      try {
        connection.close();
      } catch (JMSException e) {
        e.printStackTrace();
      }
    }
  }
}
This program produces the following output.
Received message: This is a test JMS Message
Received message: This is a test JMS Message
Received message: This is a test JMS Message
Received message: This is a test JMS Message
Read other Java tutorials from here.
Email ThisBlogThis!Share to XShare to Facebook
Newer Post Older Post Home

0 comments:

Post a Comment

Follow @StackStalk
Get new posts by email:
Powered by follow.it

Popular Posts

  • Python FastAPI file upload and download
    In this article, we will look at an example of how to implement a file upload and download API in a Python FastAPI microservice. Example bel...
  • Avro Producer and Consumer with Python using Confluent Kafka
    In this article, we will understand Avro a popular data serialization format in streaming data applications and develop a simple Avro Produc...
  • Monitor Spring Boot App with Micrometer and Prometheus
    Modern distributed applications typically have multiple microservices working together. Ability to monitor and manage aspects like health, m...
  • Server-Sent Events with Spring WebFlux
    In this article we will review the concepts of server-sent events and work on an example using WebFlux. Before getting into this article it ...
  • Accessing the Kubernetes API
    In this article, we will explore the steps required to access the Kubernetes API and overcome common challenges. All operations and communic...
  • Python FastAPI microservice with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Scheduling jobs in Python
    When developing applications and microservices we run into scenarios where there is a need to run scheduled tasks. Examples include performi...
  • Using Tekton to deploy KNative services
    Tekton is a popular open-source framework for building continuous delivery pipelines. Tekton provides a declarative way to define pipelines ...

Copyright © StackStalk