Using Topics
Sending messages to a Topic is identical to sending them to a Queue. Just obtain a Topic instead of the Queue. If you are writing a stand-alone client, use createTopic instead of createQueue to get the Topic instance.
Connection con = ...;
Session session = ...;
Topic topic = ...;
MessageConsumer consumer = session.createConsumer(topic); // subscribe (more)
con.start(); // start the connection
Now you have a non-durable subscription. You can either poll for or listen to messages, as you would on a queue.
In order to end the non-durable subscription, close either the MessageConsumer or the whole Connection:
consumer.close(); // unsubscribe (nondurable only)
Connection con = ...;
Session session = ...;
Topic topic = ...;
con.setClientID("JmsTest"); // required! (more)
MessageConsumer consumer = session.createDurableSubscriber(queue, "s1"); // subscribe (more)
con.start();
Now you have a durable subscription. If you used the same client ID and subscription name again, you connect to an existing subscription. Otherwise you create a new one.
The subscription exists until you explicitly unsubscribe by calling the unsubscribe method. Closing the MessageConsumer does not end the durable subscription.
A durable subscription must be explicitly unsubscribed (non-durable subscriptions end automatically after closing).
Session session = ...;
session.unsubscribe("s1"); // no open MessageConsumer allowed here (more)