Apache ActiveMQ - Subscriber Application

Now let's create a subscriber application which will receive message from the ActiveMQ Topic.

Create Project

Using eclipse, select FileNewMaven Project. Tick the Create a simple project(skip archetype selection) and click Next.

Enter the details, as shown below −

  • groupId − com.tutorialspoint

  • artifactId − subscriber

  • version − 0.0.1-SNAPSHOT

  • name − ActiveMQ Subscriber

Click on Finish button and a new project will be created.


Now update the content of pom.xml to include dependencies for ActiveMQ.

<project xmlns="http://maven.apache.org/POM/4.0.0" 
   <name>ActiveMQ Subscriber</name>

Now create a Subscriber class which will receive message from the ActiveMQ Queue.

package com.tutorialspoint.activemq;

import java.io.Console;

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

import org.apache.qpid.jms.JmsConnectionFactory;

public class Subscriber {
   public static void main(String[] args) throws Exception {
      // Create a connection to ActiveMQ JMS broker using AMQP protocol
      JmsConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:5672");
      Connection connection = factory.createConnection("admin", "password");

      // Create a session
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

      // Create a topic
      Destination destination = session.createTopic("MyFirstTopic");

      // Create a subscriber specific to topic
      MessageConsumer subscriber = session.createConsumer(destination);

      Console c = System.console();
      String response;
      do {      	
         // Receive the message
         Message msg = subscriber.receive();
         response = ((TextMessage) msg).getText();

         System.out.println("Received = "+response);

      } while (!response.equalsIgnoreCase("Quit"));

      // Close the connection

Subscriber class creates a connection, starts the session, creates a consumer and then receives message from topic if there is any. If topic contains quit as message then application terminates else it will keep polling queue for messages.

We'll run this application multiple times to create multiple subscribers in ActiveMQ - Test Application chapter.