How to Receive a Message from an Apache ActiveMQ Topic with JMS

W/o Durability

import static java.lang.System.out;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;

public final class ActiveMQSample {

  public static void main(final String[] args) throws Exception {
    final ConnectionFactory connFactory = new ActiveMQConnectionFactory();

    final Connection conn = connFactory.createConnection();

    final Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

    final Destination dest = sess.createTopic("SampleTopic");

    final MessageConsumer cons = sess.createConsumer(dest);

    conn.start();

    final Message msg = cons.receive();

    out.println(msg);

    conn.close();
  }

}

W/ Durability

import static java.lang.System.out;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.Topic;

public final class ActiveMQSample {

  public static void main(final String[] args) throws Exception {
    final ConnectionFactory factory = new ActiveMQConnectionFactory();

    final Connection conn = factory.createConnection();

    conn.setClientID("SampleClient");

    final Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

    final Topic dest = sess.createTopic("SampleTopic");

    final MessageConsumer cons = sess.createDurableSubscriber(dest, "SampleSubscription");

    conn.start();

    final Message msg = cons.receive();

    out.println(msg);

    conn.close();
  }

}

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s