You can combine producers and consumers in the same connection (or even session when using the unified API). In addition, the JMS API allows you to implement a request-reply pattern for your messaging operations by using temporary destinations. Temporary destinations are explicitly created and destroyed programmatically. They are maintained by the broker only for the duration of the connection in which they are created.
To set up the request-reply pattern you need to do the following:
Programmatically create a temporary destination where the consumer can send replies.
In the message to be sent, set the JMSReplyTo field of the message header to that temporary destination.
The request-reply mechanism saves an administrator the trouble of creating a destination administered object or a physical destination for the reply, and makes it easy for the consumer to respond to the request. This pattern is useful when the producer must be sure that a request message has been handled before proceeding.
Figure 2–6 illustrates a request-reply pattern that sends messages to a topic and receives replies in a temporary queue.
As the figure shows, MyTopicPublisher produces Msg1 to the destination MyTopic. MyTopicSubsriber1 and MyTopicSubscriber2 consume the message and send a reply to MyTempQueue, from which MyTempQueueReceiver retrieves it. This pattern might be useful for an application that publishes pricing information to a large number of subscribers and which queues their (reply) orders for sequential processing.
Temporary destinations last only as long as the connection in which they are created. While any producer can produce messages to a temporary destination, the only consumers that can access a temporary destination are those created in the same connection in which the temporary destination was created.
Since the request/reply pattern depends on creating temporary destinations, you should not use this pattern in the following cases:
If you anticipate that the connection in which the temporary destination was created might terminate before the reply is sent.
If reply messages need to be persistent.