Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

JMS Application Deployment Tutorial for Beginners

DZone's Guide to

JMS Application Deployment Tutorial for Beginners

· Integration Zone ·
Free Resource

Continue to drive demand for API management solutions that address the entire API life cycle and bridge the gap to microservices adoption.  

JMS or Java Messaging Service is an API for messaging (the exchange of information between two separate and independent network entities) based on Java EE. It sets a number of interfaces for sending and receiving messages. There are two messaging models supported by JMS: PTP or point-to-point and publish-subscribe. The first model (PTP) relies on the concept of message queues, where the key features are one consumer per message and no timing dependency between the sender and the receiver. The publish-subscribe model is vice versa: multiple consumers per message and a timing dependency between the sender and the receiver.

The main advantages of using JMS are:

  • Asynchronous messaging (in this case, all the parts don’t need to be up for the app to function as a whole).
  • Storage (the messages are stored on behalf of the receiver while it is down and then sends them, once it is up.)

So, as usual, let’s try out this technology in the Jelastic Cloud using the GlassFish server!

Create environment

1. Log into your Jelastic account and click Create environment.

2. Select GlassFish as your application server and specify the resource limits for it. Then, type your environment name and click Create.

jms application environment

In a few minutes your environment will appear on the Jelastic Dashboard.

JMS environment with GlassFish

Create JMS application

We're using a JMS application, written by Arun Gupta, which consists of a Sender, Receiver and a simple test servlet for checking the results of program execution.

1. Firstly, create Sender. This is a Stateless EJB that contains only one method for sending messages:

package org.sample.sendmessage;
 
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.jms.*;
 
@Stateless
public class MessageSender {
 
    @Resource(mappedName = "jms/JMSConnectionFactory")
    private ConnectionFactory connectionFactory;
 
    @Resource(mappedName = "jms/myQueue")
    Queue queue;
 
    public void sendMessage(String message) {
        MessageProducer messageProducer;
        TextMessage textMessage;
        try {
            Connection connection = connectionFactory.createConnection();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            messageProducer = session.createProducer(queue);
            textMessage = session.createTextMessage();
            //textMessage.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT);
 
            textMessage.setText(message);
            messageProducer.send(textMessage);
 
            messageProducer.close();
            session.close();
            connection.close();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

2. Now we will create Receiver, which is also EJB with a single method to receive messages synchronously:

package org.sample.sendmessage;
 
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.jms.*;
import java.util.Enumeration;
 
@Stateless
public class MessageReceiverSync {
 
    @Resource(mappedName = "jms/JMSConnectionFactory")
    private ConnectionFactory connectionFactory;
 
    @Resource(mappedName = "jms/myQueue")
    Queue myQueue;
 
    private String message;
 
    public String receiveMessage() {
        try {
            Connection connection = connectionFactory.createConnection();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            QueueBrowser queueBrowser = session.createBrowser(myQueue);
            Enumeration enumeration = queueBrowser.getEnumeration();
            while (enumeration.hasMoreElements()) {
                TextMessage o = (TextMessage) enumeration.nextElement();
               return "Receive " + o.getText();
 
            }
            session.close();
            connection.close();
        } catch (JMSException e) {
            e.printStackTrace();
        }
        return "";
    }
}

3. Finally let’s create a test servlet which connects all the parts of our code and helps us to check the results of our program execution:

package org.sample.sendmessage;
 
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
@WebServlet(urlPatterns = {"/TestServlet"})
public class TestServlet extends HttpServlet {
 
    @EJB MessageSender sender;
 
    @EJB MessageReceiverSync receiver;
 
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            out.println("");
            out.println("");
            out.println("JMS2 Send Message");
            out.println("");
            out.println("");
            out.println("JMS2 Send/Receive Message using JMS2 " + request.getContextPath() + "");
            String m = "Hello there";
            sender.sendMessage(m);
            out.format("Message sent: %1$s.", m);
            out.println("Receiving message...");
            String message = receiver.receiveMessage();
            out.println("Message rx: " + message);
            out.println("");
            out.println("");
        }
    }
 
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
 
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
 
    @Override
    public String getServletInfo() {
        return "Short description";
    }
}

4. Build the application into a WAR package.

Configure GlassFish

1. Open GlassFish in a browser and log into the GlassFish Admin Console using the credentials, which Jelastic sent you when you created the environment.

2. Java EE requires a JMS ConnectionFactory to be configured and accessible to the application under the JNDI name. Firstly, navigate to JMS Resources and create a new factory called jms/JMSConnectionFactory with javax.jms.QueueConnectionFactory type.

JMS Connection Factory

3. Select gfcluster as a target and save the changes.

JMS Connection Factory Target

4. Navigate to Destination Resources and create jms/myQueue queue called Queue with javax.jms.Queue type. The target is also gfcluster.

JMS Destination Resource

Deploy JMS Application

1. Navigate to the Applications tab, upload your application package and deploy it to the send-message context of the GlassFish cluster.

JMS Application Deployment

2. Launch your JMS application in a web browser to check the results.

JMS Application

As you can see any application, even complex ones work in the Jelastic Cloud like a charm. Don’t just take our word for it. Try Jelastic and receive immediate access to your free 2 week free trial!

Discover how organizations are modernizing their application architectures for speed and agility from the growing API economy

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}