Browse DevX
Sign up for e-mail newsletters from DevX


Master JMS Messaging with OpenJMS  : Page 3

Learn how to take advantage of Java's Messaging Service API (JMS) with the free OpenJMS implementation. You'll see how to send and receive messages using both point-to-point and publish/subscribe messaging models.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Synchronous and Asynchronous Retrieval
Retrieving a message synchronously is similar to the process of writing to the queue, but instead of using a QueueSender object, you use a QueueReceiver object. You must also call the start() method on the queue connection, which starts the delivery of incoming messages. After doing that, you receive messages by calling the synchronous receive() method, as shown in the QueueReceiveSynchronous class below.

public class QueueReceiveSynchronous { public static void main(String[] args) { try { // standard boilerplate code to establish a JNDI // context and connection // retrieve queue connection factory QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory)context.lookup( "JmsQueueConnectionFactory"); // create a queue connection QueueConnection queueConnection = queueConnectionFactory.createQueueConnection(); // start delivery of incoming messages queueConnection.start(); // create a queue session // set transactions to false and set auto // acknowledgement of receipt of messages QueueSession queueSession = queueConnection.createQueueSession( false,Session.AUTO_ACKNOWLEDGE); // retrieve queue Queue queue = (Queue)context.lookup("queue1"); // create a queue receiver and associate // to the retrieved queue QueueReceiver queueReceiver = queueSession.createReceiver(queue); // receive message using the synchronous // receive method Message message = queueReceiver.receive(); String messageText = null; if (message instanceof TextMessage) messageText = ((TextMessage)message).getText(); System.out.println(messageText); // clean up ... } catch (NamingException e) { e.printStackTrace(); } catch (JMSException e) { e.printStackTrace(); } } }

Asynchronous Retrieval
To listen asynchronously to the queue, register an object that implements the MessageListener interface, that simply requires you to implement the onMessage method, in which you process the incoming message as desired. The QueueReceiveAschynchronous class shown in Listing 1 receives messages asynchronously.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date