Publish-Subscribe Messaging

Publish-subscribe messaging involves one or more MessageProducers “publishing” messages to a particular topic, and one or more MessageConsumers “subscribing” to the topic and receiving any messages published to it. The JMS provider is responsible for delivering a copy of any message sent to a topic to all subscribers of the topic at the time that the message is received. Unlike point-to-point messaging, where messages are kept on the queue until a receiver reads them, any messages received at a topic while a subscriber is not active (e.g., hasn’t subscribed to the topic yet, or subscribed and then went out of scope or exited) are lost with respect to that subscriber.

Publish-subscribe messaging is performed in JMS using the topic-related interfaces and classes in the javax.jms package. Topics are represented by Topic objects, which are looked up in JNDI from the JMS provider. TopicConnectionFactory objects are looked up in JNDI as well, and used to create TopicConnections. TopicConnections and Topics are used to create TopicSessions, which are in turn used to create TopicPublishers and TopicSubscribers.

Sample Client

Example 10-3 shows a publish-subscribe client, PubSubMessagingClient, that mirrors the PTPMessagingClient in Example 10-2. The structure and function of the client is virtually identical to that described for the PTPMessagingClient, except that topics, subscribers, and publishers are used instead of queues, receivers, and senders. The ...

Get Java Enterprise in a Nutshell, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.