Apache ActiveMQ - Publisher Application

Now let's create a publisher application which will send message to the ActiveMQ Queue.

Create Project

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

Enter the details, as shown below−

  • groupId − com.tutorialspoint

  • artifactId − publisher

  • version − 0.0.1-SNAPSHOT

  • name − ActiveMQ Publisher

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 Publisher</name>

Now create a Publisher class which will send message to the ActiveMQ topic to broadcast it to all the subscribers.

package com.tutorialspoint.activemq;

import java.io.Console;
import java.util.Scanner;

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

import org.apache.qpid.jms.JmsConnectionFactory;

public class Publisher {
   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 publisher specific to topic
      MessageProducer publisher = session.createProducer(destination);

      Scanner input = new Scanner(System.in);
      String response;
      do {
         System.out.println("Enter message: ");
         response = input.nextLine();
         // Create a message object
         TextMessage msg = session.createTextMessage(response);

         // Send the message to the topic

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

      // Close the connection

Producer class creates a connection, starts the session, creates a producer and then asks user to enter message. If user enters quit then application terminates else it will send the message to the topic.

We'll run this application in ActiveMQ - Test Application chapter.