Java

Java JMS Example With Producer and Consumer

We will See here JMS Concept with “Java JMS Example”, also we will see Producer, Consumer and how we can send or receive any messages to Queues or Topics. So that we can implement JMS easily in our any Java Project.

Java JMS Example

JMS | Java Message Service :

  • JMS (Java Message Service) API is Message Orriented Middleware (MOM), which helps us to send message between two or more clients.
  • It is loosely coupled, reliable and asynchronous messaging service. We will see here Java JMS Example also.

 

JMS Destinations :

In JMS there are two types of Destinations :

  1. Queue
    • In JMS queue one-to-one communication will be there.
    • The message will be received by only one of the consuming receivers.
    • Messages sent to a queue are stored on disk or memory until someone picks it up or it expires. So queues need some active storage management.
  2. Topics
    • In JMS topic one-to-many communication will be there.
    • The same published message can be received by other consumer also.
    • We can also call this as ‘broadcast’ model.
    • For topic’s the message delivery is ‘fire-and-forget’ – if no one listens, the message just disappears, but we can manage this using ‘Durable Subscriber’.

Note : For more details about Queue and Topics, you can check –

 

JMS Models :

JMS API Supports two Models :

  1. Point to Point  (For Queues)
  2. Publish & Subscribe (For Topics)

1. Point to Point :

  • Point-to-Point Messaging model supports only Queues, its not for Topics.
  • Here Producer will send message to Queue and Consumer will receive that message.
  • Here guarantee will be there to deliver the message.
  • Any number of producers and consumers can exist. At any time and situation each message is taken by only one consumer.
Java JMS Example_pointToPoint
2. Publish & Subscribe :
  • Publish-Subscribe Messaging model supports only Topics, its not for Queues.
  • Here Publisher will publish message to Topic and Subscriber will subscribe and then receive that message.
  • Any number of publishers and subscribers can exist. Each message can be taken by any number of consumers.
Java JMS Example-publish-Subscribe

JMS Architecture / Model :

Java JMS Example_jms architecture

“Here First we need to Create Connection Factory and then with the help of Connection Factory we need to create Connections. After Creating Connections we need to create Session and then create message and Producer/Consumer. Only after creating all those things we can send message to any JMS Client.”

  • Connection Factory : It is nothing but Such type of Object, which help us to create JMS Connections from JMS Client. Below is sample to create Connection Factory.
//Creating Connection Factory for Tibco JMS Client

TibjmsConnectionFactory connectionFactory = new TibjmsConnectionFactory("tcp://localhost:7222");
connectionFactory.setUserName(USERNAME);
connectionFactory.setUserPassword(PASSWORD);
  • Connection : It is such type of link, we can say to communicate with JMS Client. By the help of Connection Factory we can create Connections. 
//Creating Connection with the help of Connection Factiory which we created above

Connection connection = connectionFactory.createConnection();
connection.start();
  • Session : It’s simply means a particular interval of time. By the help of Connection we can create Session.
//Creating Session with the help of Connection which we created above

Session session = connection.createSession(true,Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue(queueName);
  • Producer : It’s nothing but our Client, which is going to send message. By the help of Session we can create Producer.
//Creating Producer with the help of Session which we created above

MessageProducer producer = session.createProducer(null);
  • Consumer : It’s our receiver Client. It will receive message which will send by Producer. 
//Creating Consumer with the help of Session which we created above

MessageConsumer consumer = session.createConsumer(destination);
  • Message : It will be our actual message, which is going to send between Producer and Consumer. After Sending or Receiving message we need to commit and close the session and connection.
    • For Message Sending :
//Creating Message and then sending that message to Client with help of Session and Producer

TextMessage message = session.createTextMessage();
producer.send(message);
session.commit();
session.close();
connection.close();
    • For Message Receiving :
//Creating Message and then Receiving that message with the help of Session and Connection

TextMessage message = session.createTextMessage();
message = (TextMessage) consumer.receive();
session.commit();
session.close();
connection.close();
  • Destination : We can say it’s such type of channel through which our message will travel. It may be Queue or Topic.
    • If we talk about tibco ems, we can use below command to create a queue or topic.
Java JMS Example_QueueTopic Creation

NOTE : If you want more details about destination, then have a look – Destinations.

Java JMS Example | Sending and Receiving Data from Tibco EMS Queue on Java / Spring Boot Application:

Now here we will create, a simple Java JMS Example with  “Spring boot application” where a job will execute in every hour (Scheduler) and it will send some message to above created queue – study4online and then we will receive that message also. Lets go…

First we will add below 3 .jar files in our application.

  1. jms-2.0.jar
  2. tibcrypt.jar
  3. tibjms.jar

 

Folder Structure :

Java JMS Example_FolderStructure

Dependency :

We need to add below Dependencies :

org.springframework.boot
spring-boot-starter-activemq

 

Code :

package com.study4online;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class JmsDemoApplication {

public static void main(String[] args) {
SpringApplication.run(JmsDemoApplication.class, args);
}

}
package com.study4online.config;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;

import com.tibco.tibjms.TibjmsConnectionFactory;

@Configuration
@EnableJms
public class JmsTemplateConfig {

//Sending Queue Message
public void sendQueueMessage(String url, String queueName, String msg, String userName, String password)
throws Exception {

// Creating Connection Factory
TibjmsConnectionFactory connectionFactory = new TibjmsConnectionFactory(url);
connectionFactory.setUserName(userName);
connectionFactory.setUserPassword(password);

// Creating Connection
Connection connection = connectionFactory.createConnection();
connection.start();

// Creating Session
Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue(queueName);

// Creating Producer
MessageProducer producer = session.createProducer(null);

// Creating TextMessage
TextMessage txtMessage = session.createTextMessage();
txtMessage.setText(msg);

// Sending Message
producer.send(destination, txtMessage);
System.out.println("Message : " + msg + " Sent to Queue :" + queueName);

session.commit();
session.close();
connection.close();
}

//Receiving Queue Message
public void receiveQueueMessage(String url, String queueName, String userName, String password) throws Exception {

TibjmsConnectionFactory connectionFactory = new TibjmsConnectionFactory(url);
connectionFactory.setUserName(userName);
connectionFactory.setUserPassword(password);

Connection connection = connectionFactory.createConnection();
connection.start();

Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue(queueName);

MessageConsumer consumer = session.createConsumer(destination);
TextMessage message = session.createTextMessage();
message = (TextMessage) consumer.receive();
System.out.println("Message which received :" + message);

session.commit();
session.close();
connection.close();
}

}
package com.study4online.scheduler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.study4online.config.JmsTemplateConfig;

@Component
public class MyScheduler {
Logger logger = LoggerFactory.getLogger(MyScheduler.class);

@Autowired
JmsTemplateConfig jmsTemplateConfig;

@Scheduled(fixedDelay = 900000)
public void run() throws Exception {
logger.info("Timmer Job : Current Time is : " + new java.util.Date());

String url = "tcp://localhost:7222";
String userName = "";
String password = "";
String queueName = "study4online";
String message = "Hello we are learning JMS";

// Sending Message to Queue
jmsTemplateConfig.sendQueueMessage(url, queueName, message, userName, password);

// Receiving Message to Queue
jmsTemplateConfig.receiveQueueMessage(url, queueName, userName, password);

}

}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.study4online</groupId>
<artifactId>JMSDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>JMSDemo</name>
<description>Spring_JMS_Demo</description>

<properties>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

Output (After executing Send Method):

In below Screen we can see “Message sent successfully”, on “EMS Server”. On Server also we can see it’s showing 1 Pending message. Now we will execute receiver method.

Java JMS Example_MessageSentSucesssfully
Java JMS Example_PendingMessage

Output (After executing receive method) :

In Below Screen we can see our message got received successfully, and also we can see on Server “No pending Messages” are there.
Java JMS Example_Message_Received
Java JMS Example_NoPendingMessage

We show above “Java JMS Example” step by step with code, If you want to download this JMS Example then click on below Download Link.

Help Others, Please Share

Leave a Reply

avatar
  Subscribe  
Notify of