A Simple JMS application with ActiveMQ

Today in my blog I am going to write about how to implement a simple application in JMS. As the message broker I am using ActiveMQ.

Prerequisites:

  • You should have ActiveMQ available with you. You can download ActiveMQ here.
  • Extract the zip folder in to some where.
  • To start ActiveMQ in Unix, open a terminal and go inside the bin folder of ActiveMQ directory. Then type the following commands.
    • cd %ActiveMQHome%/bin
    • ./activemq start
  • Go to http://localhost:8161/admin/index.jsp and you can see the ActiveMQ console.
  • Create a JMS project (I am using Intellj Idea).
  • Then you should import the ActiveMQ libraries to this project. Within the downloaded package you can see a .jar folder called activemq-all-5.12.1.jar. Import this in to your project.
  • Now we are ready to create the first JMS application using ActiveMQ.

ProgrammingModel

Figure 1 – The JMS API Programming Model

Step 1: First of all we are going to create the message sender. (For an overview of JMS, you can visit my blog here)

package sample;

import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Properties;

/*
* The following class implements a simple message sender using ActiveMQ as the message broker
*/

public class Sender {

    private String queueName = "queue1";
    private String url = "tcp://localhost:61616";
    private boolean transacted = false;

    public void sendMessage(){
        /*
        *JNDI properties required for the initial context.
        *As I am using ActiveMQ, I have given the ActiveMQInitialContextFactory as the initial context factory.
        *This will be used when create the initial factory.
        */

        Properties properties = new Properties();
        properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory");
        properties.setProperty(Context.PROVIDER_URL, url);
        properties.setProperty("queue.queue1", queueName);

        try {
            //Create the initial context using the defined properties.
            Context context = new InitialContext(properties);

            //Lookup for the connection factory in this context.
            ConnectionFactory factory = (ConnectionFactory)context.lookup("ConnectionFactory");

            //Using the connection factory, create the connection object.
            Connection connection = factory.createConnection();

            //start the connection
            connection.start();

            //create a session object using the connection object
           //transacted variable has the value false. That is, this session is not a transacted session.
           //The second argument means that the session will automatically acknowledge the receipt of messages.
            Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);
            
           //the destination for the message is a queue.
            Destination destination = (Destination)context.lookup("queue1");

            //Create a message producer from the session with the defined destination
            MessageProducer producer = session.createProducer(destination);

            //Create a text message using the session.
            TextMessage message = session.createTextMessage();
            message.setText("Sample message...");

            //send the message to the destination
            producer.send(message);
            System.out.println("Sent: " + message.getText());

            //Remember to close the connection, producer and the session.
            System.out.println("Connection is closing...");
            producer.close();
            session.close();
            connection.close();

        } catch (NamingException e) {
            e.printStackTrace();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Sender mySender = new Sender();
        mySender.sendMessage();
    }
}

 

Note: You can close both the session and connection just by closing the connection.

Step 2: Then we create the message consumer.

package sample;

import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Properties;

/**
 * The following class implements a simple message receiver using ActiveMQ as the message broker
 */
public class Consumer {
    private String queueName = "queue1";
    private String url = "tcp://localhost:61616";
    private boolean transacted = false;

    public void receiveMessage(){

        /*
        *JNDI properties required for the initial context.
        *As I am using ActiveMQ, I have given the ActiveMQInitialContextFactory as the initial context factory.
        *This will be used when create the initial factory.
        */

        Properties properties = new Properties();
        properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory");
        properties.setProperty(Context.PROVIDER_URL, url);
        properties.setProperty("queue.queue1", queueName);

        try {
            //Create the initial context using the defined properties.
            Context context = new InitialContext(properties);

            //Lookup for the connection factory in this context.
            ConnectionFactory factory = (ConnectionFactory)context.lookup("ConnectionFactory");

            //Using the connection factory, create the connection object.
            Connection connection = factory.createConnection();

            //start the connection
            connection.start();

            //create a session object using the connection object
	        //transacted variable has the value false. That is, this session is not a transacted session.
	        //The second argument means that the session will automatically acknowledge the receipt of messages.
            Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);

            //the destination for the message is a queue.
            Destination destination = (Destination)context.lookup("queue1");

            //Create a message consumer from the session with the defined destination
            MessageConsumer consumer = session.createConsumer(destination);

            //explicitly receive the message
            Message message = consumer.receive();

            //check whether there is a message and whether it is a text message.
            if(message != null && message instanceof TextMessage){

                //Convert the message in to a text message
                TextMessage textMessage = (TextMessage)message;
                //print the message text
                System.out.println("Received: " + textMessage.getText());
            }

            //Remember to close the connection
            System.out.println("Connection is closing...");
            consumer.close();
            session.close();
            connection.close();

        } catch (NamingException e) {
            e.printStackTrace();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Consumer consumer = new Consumer();
        consumer.receiveMessage();
    }
}

 

Step 3: To run the application, first you run the Sender.java. Then the following will be the output in console:

op1

Figure 2 – Output in the console after running the Sender.java

The output at the ActiveMQ Console will be as following:

op2

Figure 3 – The output at the ActiveMQ Console after running Sender.java

Step 4: Then run the Consumer.java class. The output in the console will be as following:

op3

Figure 4 – Output in the console after running the Consumer.java

The output at the ActiveMQ Console after running Consumer.java will be as following:

op4

Figure 5 – Output at ActiveMQ console after running Consumer.java

Now you know how to implement a simple JMS application using ActiveMQ.

Advertisements

One thought on “A Simple JMS application with ActiveMQ

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s