This example demonstrates how to use a durable subscription with ActiveMQ.
Durable subscriptions are a standard part of JMS, please consult the JMS 1.1 specification for full details.
Unlike non durable subscriptions, the key function of durable subscriptions is that the messages contained in them persist longer than the lifetime of the subscriber - i.e. they will accumulate messages sent to the topic even if the subscriber is not currently connected. They will also survive server restarts. Note that for the messages to be persisted, the messages sent to them must be marked as persistent messages.
To run the example, simply type mvn verify
from this directory
client-jndi.properties
file in the directory ../common/config
initialContext = getContext();
Topic topic = (Topic) initialContext.lookup("/topic/exampleTopic");
ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("/ConnectionFactory");
connection = cf.createConnection();
connection.setClientID("durable-client");
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer messageProducer = session.createProducer(topic);
TopicSubscriber subscriber = session.createDurableSubscriber(topic, "subscriber-1");
TextMessage message1 = session.createTextMessage("This is a text message 1");
messageProducer.send(message1);
TextMessage messageReceived = (TextMessage)subscriber.receive();
TextMessage message2 = session.createTextMessage("This is a text message 2");
messageProducer.send(message2);
subscriber.close();
subscriber = session.createDurableSubscriber(topic, "subscriber-1");
messageReceived = (TextMessage)subscriber.receive();
subscriber.close();
session.unsubscribe("subscriber-1");
finally
block. Closing a JMS connection will automatically close all of its sessions, consumers, producer and browser objects
finally
{
if (initialContext != null)
{
initialContext.close();
}
if (connection != null)
{
connection.close();
}
}