DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Getting Started With JMS-ActiveMQ: Explained in a Simple Way
  • From J2EE to Jakarta EE
  • A Systematic Approach for Java Software Upgrades
  • How to Quarantine a Malicious File in Java

Trending

  • Build a Simple REST API Using Python Flask and SQLite (With Tests)
  • MCP Servers: The Technical Debt That Is Coming
  • System Coexistence: Bridging Legacy and Modern Architecture
  • Optimizing Integration Workflows With Spark Structured Streaming and Cloud Services
  1. DZone
  2. Coding
  3. Java
  4. JMS Queue Server and Client Example Based On an ActiveMQ Provider

JMS Queue Server and Client Example Based On an ActiveMQ Provider

The basics of messaging services for Java apps, along with a client example based on ActiveMQ.

By 
Tomasz J-ski user avatar
Tomasz J-ski
·
Jan. 16, 16 · Opinion
Likes (3)
Comment
Save
Tweet
Share
22.9K Views

Join the DZone community and get the full member experience.

Join For Free

What is JMS?

Java Message Service could be considered as high level framework that communicates two or more clients each other by sending messages. JMS is fully supported by Java EE and has been described in JSR -914 (see links section).

Here are the base operations that we can do:

  • Send messages

  • Receive messages

Typically, one client creates a message and sends it to the JMS server, and another client receives it and performs some kind of operation. Of course, this is a high level overview, and low level processes are more complicated.

Where Do We Use It?

Well we could use JMS everywhere where we need to increase scalability, integrate different environments, include batch processing support, or asynchronous communication without time pressure.

A common use is  to send email, the client creates an email message from the template, and sends it to the MQ server. The receiver then receives the message from MQ server and sends the email.

But as you can see there are many other processes that could be implemented that way.

Sample MQ Providers List?

  • Amazon SQS

  • ActiveMQ

  • Oracle Weblogic

  • HornetQ (previously JBoss messaging) see link number 2.

What is ActiveMQ?

ActiveMQ is an implementation of Message Oriented Middleware which is used to communicate via JMS clients. As we can read at the official page (see link number 3), it is an open source system that is fast, supports cross language clients and protocols, and, most importantly, fully supports JMS 1.1 specifications.

The latest version is 5.13.0, and this version will be used in the demo.

ActiveMQ Server

From the download section of the official ActiveMQ page (see link number 3), you can download the latest server binary package. After un-zipping, it took almost 100MB of disk space. Unzipped binaries are all you need to start your server.

My Windows machine starting script is located at: apache-activemq-5.13.0\bin. I use activemq.bat but there are similar scripts for Linux too.

Bat script setup local env and finally run the jar file called activemq.jar, which is located at bin folder.

After running in the command line, starting the script, and successfully starting the server you should see something similar to this:

Image title

Now you could type http://localhost:8161/admin/ to access Your ActiveMQ server administration console, note that the default login and password is admin.

It should look like this:

Image title

Now you could add your first queue in the Queues menu.

ActiveMQ Client Example

I created a sample client for an ActiveMQ server in Java 8 using threads and lambdas. You can find all the code at my GitHub: https://github.com/tjancz/jms-activemq-example.git

Below you can see the sender code:

package it.janczewski.examples.utils;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jms.*;
import java.math.BigInteger;
import java.security.SecureRandom;

public class Sender {
    private final Logger logger = LoggerFactory.getLogger(Sender.class);
    private SecureRandom random = new SecureRandom();

    public void createTask(){
        String taskName = generateTaskName();
        Runnable sendTask = () -> {
            ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
            Connection connection = null;
            try {
                connection = connectionFactory.createConnection();
                connection.start();
                Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                Destination destination = session.createQueue("TJ Test");
                MessageProducer producer = session.createProducer(destination);
                producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
                String text = "Hello from: " + taskName + " : " + this.hashCode();
                TextMessage message = session.createTextMessage(text);
                logger.info("Sent message hash code: "+ message.hashCode() + " : " + taskName);
                producer.send(message);
                session.close();
                connection.close();
            } catch (JMSException e) {
                logger.error("Sender createTask method error", e);
            }
        };
        new Thread(sendTask).start();
    }

    private String generateTaskName() {
        return new BigInteger(20, random).toString(16);
    }
}

And the receiver code:

package it.janczewski.examples.utils;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.jms.*;

public class Reciver implements ExceptionListener{
    private final Logger logger = LoggerFactory.getLogger(Reciver.class);

    public void createRecieveTask() {
        Runnable recTask = () -> {
            try {
                ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
                Connection connection = connectionFactory.createConnection();
                connection.start();
                connection.setExceptionListener(this);
                Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                Destination destination = session.createQueue("TJ Test");
                MessageConsumer consumer = session.createConsumer(destination);
                Message message = consumer.receive(4000);
                if (message instanceof TextMessage) {
                    TextMessage textMessage = (TextMessage) message;
                    String text = textMessage.getText();
                   logger.info("Received TextMessage object: " + text);
                } else {
                    logger.info("Received other object type with message: " + message);
                }
                consumer.close();
                session.close();
                connection.close();

            } catch (JMSException e) {
                logger.error("Reciver createRecieveTask method error", e);
            }
        };
        new Thread(recTask).start();
    }

    @Override
    public void onException(JMSException exception) {
        logger.error("Recieve error occured.");
    }
}

If you would like to see all working stuff, just clone it from my GitHub repo.

There is also great documentation on the ActiveMQ page.

Summary

JMS is not scary as it looks and, ActiveMQ is a great MOM that could easily help you set up message queues and integrate different systems.

Links

    1. https://jcp.org/aboutJava/communityprocess/final/jsr914/index.html
    2. http://hornetq.jboss.org/
    3. http://activemq.apache.org/
Open source Links Java Message Service Message oriented middleware Java EE Batch processing Java (programming language) GitHub

Opinions expressed by DZone contributors are their own.

Related

  • Getting Started With JMS-ActiveMQ: Explained in a Simple Way
  • From J2EE to Jakarta EE
  • A Systematic Approach for Java Software Upgrades
  • How to Quarantine a Malicious File in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!