How to receive a synchronous jms message

This tutorial requires that you have glassfish installed and followed the following previous 2 tutorials:

http://czetsuya-tech.blogspot.com/2012/06/how-to-setup-set-jms-factory-and-queue.html
http://czetsuya-tech.blogspot.com/2012/06/how-to-send-jms-message-to-jms-queue.html

For simplicity, we will just extend the JMSSender class that we have defined from the previous tutorial and add the ff method:

public void getMessages() throws JMSException {
 ObjectMessage objectMessage;

 QueueConnection connection = null;
 QueueSession session = null;
 QueueReceiver queueReceiver = null;
 boolean goodByeReceived = false;
 try {
  connection = openQueueConnection();
  session = connection.createQueueSession(transacted,
    QueueSession.AUTO_ACKNOWLEDGE);
  queueReceiver = session.createReceiver(queue);
  connection.start();
  while (!goodByeReceived) {
   log.debug("[xxx-commons] Waiting for messages...");
   objectMessage = (ObjectMessage) queueReceiver.receive();
   MessageDTO message = MessageDTOHelper
     .deserialize(objectMessage);
   if (message != null) {
    log.debug("[xxx-commons] Received the following message: ");
    log.debug("[xxx-commons] message: " + message.toString()
      + " : " + message.getRequestId());
   }
   if (message.getRequestId() != null
     && message.getRequestId().equals("7d")) {
    goodByeReceived = true;
   }
  }
  log.debug("[xxx-commons] jms receive done");
 } finally {
  closeQueueReceiver(queueReceiver);
  closeSession(session);
  closeConnection(connection);
 }
}
This method will read from the queue that we have defined. Note that queueReceiver.receive() without parameter will block until there's a jms message in queue.

 Tip you can create a generic jms receiver class that you can extend for different DTOs.
How to receive a synchronous jms message How to receive a synchronous jms message Reviewed by Edward Legaspi on Monday, June 25, 2012 Rating: 5

No comments:

Powered by Blogger.