Show TOC

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

Use

To send messages to a queue you have to create a message sender.

Procedure

Creating a Message Producer

To create a message sender, use the following code:

// create a message producer
        QueueSender queueSender = queueSession.createSender(queue);

Having obtained a QueueSender , use it to send messages to the specified queue.

Creating a Message Consumer

In the point-to-point messaging scenario, you can choose between the following two ways to receive messages:

  • If you want to receive messages asynchronously, implement the MessageListener interface. Then use the onMessage(javax.jms.Message ) method to receive the messages:

    public class Example_class implements 
               javax.jms.MessageListener {
       
                  ...
                  // create a queue receiver
                  QueueReceiver queueReceiver =  
              queueSession.createReceiver(queue);
                  // set a message listener
                  queueReceiver.setMessageListener(this);
                  ...
     
              public void onMessage(javax.jms.Message message) {
                // process the message
    Note

    Having asynchronous method from a servlet or from stateless EJB is not recommended and may not work on some J2EE servers. The preferred way would be to create a MDB instead.

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

    // create subscriber to a queue
            QueueReceiver queueReceiver = queueSession.createReceiver(queue);
     
           // receive message
           TextMessage textMessage = (TextMessage) queueReceiver.receive();