Show TOC

 Creating a Message Producer and Consumer for a TopicLocate this document in the navigation structure

Use

To send messages to a certain topic, you have to create a topic publisher. 

Procedure

Creating a Message Producer

Create a topic publisher using the following code:

TopicPublisher topicPublisher =                topicSession.createTopicPublisher(topic);

For more information, see Topic Publisher Example .

Creating a Message Consumer

Here we refer to synchronous and asynchronous todescribe how a JMS consumer application receives messages. The overall JMS client-to-client communication process itself is always asynchronous, since the producer application only waits until the message is received by the JMS Provider, not until the message is successfully received and processed by the consumer, to complete its next task.

You can use the TopicSubscriber in two ways:

  • If you want to receive messages asynchronously, you must register the class as a MessageListener instance. This enables you to receive the messages in the onMessage(Message) method:
    Note
    // create subscriber to a topic
    TopicSubscriber topicSubscriber = topicSession.createSubscriber(topic);
     
    // set message listener
    topicSubscriber.setMessageListener(this);
     
    public void onMessage(javax.jms.Message message) {
    // process the message

    For an example of receiving messages asynchronously, see Asynchronously Receiving Messages Sent to a Topic .

  • If you want to receive messages synchronously, use the receive() method.

// create subscriber to a topic
TopicSubscriber topicSubscriber = topicSession.createSubscriber(topic);
 
     
 
// receive a text message
TextMessage textMessage = (TextMessage) topicSubscriber.receive();

For an example of receiving messages synchronously, see Synchronously Receiving Messages Sent to a Topic .