Browse DevX
Sign up for e-mail newsletters from DevX


Advanced JMS Messaging with OpenJMS : Page 3

Learn to use the more advanced features of OpenJMS to filter messages, create clients that can receive messages sent even when they aren't running, and create persistent messages that can survive a provider failure.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Durable Subscriptions
As stated earlier, the examples in this and the first article in this series have a requirement that the consuming subscribing application had to be running when a publisher was publishing—otherwise, the messages would be lost. You can mitigate this message loss with durable subscriptions. In a durable subscription, the JMS server will hold messages for a client subscriber after it has formally subscribed. Durable topic subscriptions receive messages published while the subscriber is not active. Subsequent subscriber objects specifying the identity of the durable subscription can resume the subscription in the state it was left by the previous subscriber. In OpenJMS, the topic "topic1" is a durable topic.

Note that a client must designate itself as a durable subscriber before the JMS server can start holding messages for the client. The DurableSubscriberExample class shows the subscriber that listens on topic1.

The line below from the example code shows how to create a durable topic subscriber:

// create a durable topic subscriber and associate it // to the retrieved topic durableTopicSubscriber = topicSession.createDurableSubscriber( topic,"DoNotDrop");

As shown above, you create the TopicSubscriber object with the createDurableSubscriber method of the TopicSession object. The method takes two arguments, the topic name and a string that specifies the name of the subscription. In the snippet above, this was "DoNotDrop"

You can try things out by running DurableSubscriberExample to first register the durable subscriber with the JMS server. Then kill the application and run PublishToTopic. If you were working with a non-durable subscription, the messages would be lost. However, if you now run DurableSubscriberExample again, you'll see that you are still able to receive the messages published while the subscriber application was not running.

To delete a durable subscription on the JMS provider, close the subscriber and then use the unsubscribe method, specifying the subscription name as an argument:

durableTopicSubscriber.close(); topicSession.unsubscribe("DoNotDrop");

You can use the code above to delete the state the JMS provider maintains for the subscriber.

Thanks for your registration, follow us on our social networks to keep up-to-date