Show List

Durable subscribers

In JMS Publish/Subscribe (Pub/Sub) messaging, a durable subscriber is a type of subscriber that continues to receive messages even if it is not currently active (i.e., its JMS session is closed). A durable subscriber is identified by a unique client ID and a subscription name. When a durable subscriber subscribes to a topic, the JMS provider stores a record of this subscription. When a message is published to the topic, the JMS provider will keep a copy of the message until it is delivered to the durable subscriber or until it expires.

Here is an example of durable subscribers in JMS Pub/Sub in Java:

  1. The publisher creates a JMS Connection and Session, and looks up the destination topic.
Connection connection = ...; // create JMS Connection
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Topic destination = session.createTopic("MyTopic");
  1. The publisher creates a MessageProducer and sends the message to the destination topic.
MessageProducer producer = session.createProducer(destination);
TextMessage message = session.createTextMessage("Hello World");
producer.send(message);
  1. The durable subscriber creates a JMS Connection, sets the client ID, and creates a Session.
Connection connection = ...; // create JMS Connection
connection.setClientID("MyDurableSubscriber");
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
  1. The durable subscriber creates a TopicSubscriber with a subscription name and receives the message from the destination topic.
Topic destination = session.createTopic("MyTopic");
TopicSubscriber subscriber = session.createDurableSubscriber(destination, "MySubscription");
Message message = subscriber.receive();
if (message instanceof TextMessage) {
   System.out.println("Received message: " + ((TextMessage) message).getText());
}
Note that when a durable subscriber closes its JMS session, it remains subscribed to the topic, and will continue to receive messages when it reconnects. The subscriber must also be closed explicitly, either by closing the JMS connection or by unsubscribing from the topic.

    Leave a Comment


  • captcha text