In the publish/subscribe domain, message producers are called publishers and message consumers are called subscribers. They exchange messages by means of a destination called a topic: publishers produce messages to a topic; subscribers subscribe to a topic and consume messages from a topic.
Figure 2–3 shows a simple messaging operation in the publish/subscribe domain. MyTopicPublisher publishes Msg1 to the destination MyTopic. Then, MyTopicSubscriber1 and MyTopicSubscriber2 each receive a copy of Msg1 from MyTopic.
While the publish/subscribe model does not require that there be more than one subscriber, two subscribers are shown in the figure to emphasize the fact that this domain allows you to broadcast messages. All subscribers to a topic get a copy of any message published to that topic.
Subscribers can be non-durable or durable. The broker retains messages for all active subscribers, but it only retains messages for inactive subscribers if these subscribers are durable.
Figure 2–4 shows a more complex picture of publish/subscribe messaging to illustrate the possibilities offered by this pattern. Several producers publish messages to the Topic1 destination. Several subscribers consume messages from the Topic1 destination. Unless, a subscriber is using a selector to filter messages, each subscriber gets all the messages published to the topic of choice. In Figure 2–4, MyTSubscriber2 has filtered out Msg2.
This more complex picture illustrates a number of additional points about publish/subscribe messaging.
More than one producer can publish messages to a topic. Producers can share a connection or use different connections, but they can all access the same topic.
More than one subscriber can consume messages from a topic. Subscribers retrieve all messages published to a topic unless they use selectors to filter out messages or the messages expire before they are consumed.
Subscribers can share a connection or use different connections, but they can all access the same topic.
Durable subscribers can be active or inactive. The broker retains messages for them while they are inactive.
Publishers and subscribers can be added and deleted dynamically at runtime, thus allowing the messaging system to expand or contract as needed.
Messages are published to a topic in the order sent, but the order in which they are consumed depends on factors such as message expiration date, message priority, and whether a selector is used in consuming messages.
Publishers and subscribers have a timing dependency: a topic subscriber can consume only messages published after it has created the subscription.
The main advantage of the publish/subscribe model is that it allows messages to be broadcast to subscribers.