ActiveMQ using a single connection for multiple consumers

We had a need to test this, as a WebMethods installation that uses what they call Triggers had the configuration noted in the title of the post.

Not much other detail, just an example for someone who may wander by the prairie…

import java.net.URISyntaxException;
import java.util.Enumeration;

import javax.jms.*;

import org.apache.activemq.ActiveMQConnectionFactory;

public class ConsumeQueue implements Runnable {

  public static ConnectionFactory connectionFactory;
  public static Connection connection;
  public static void main(String[] args) throws URISyntaxException, Exception {
    String user = "admin";
    String password = args[0];
    //this is our hardcoded list of brokers
    String url = "failover:(tcp://host01:61616,tcp://host02:61616)";

    connectionFactory = new ActiveMQConnectionFactory(user,password,url);
    connection = connectionFactory.createConnection();

    for (int i = 1; i<= 15; i++) {
      ConsumeQueue cq = new ConsumeQueue();
    }
  }

  ConsumeQueue() {
    Thread t = new Thread(this);
    t.start();
  }

  public void run() {
    try {
      Session session = ConsumeQueue.connection.createSession(false,  Session.AUTO_ACKNOWLEDGE);
      Queue queue = session.createQueue("CustomerOrder.ATG.ESB");
      connection.start();
      MessageConsumer consumer = session.createConsumer(queue);
      while (true) {
        Message message = (Message) consumer.receive();
        if (null != message) {
          System.out.println("received msg:" + message.toString());
        }
      }
    }
    catch (Exception e) {
	  e.printStackTrace();
    }
    finally {
      if (connection != null) {
		try {
          connection.close();
	    }
	    catch (Exception e2) {
		}
      }
    }
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.