This example shows you how to use a QueueRequestor with ActiveMQ.
JMS is mainly used to send messages asynchronously so that the producer of a message is not waiting for the result of the message consumption.
However, there are cases where it is necessary to have a synchronous behavior: the code sending a message requires a reply for this message
before continuing its execution.
A QueueRequestor facilitates this use case by providing a simple request/reply abstraction on top of JMS.
The example consists in two classes:
TextReverserService
QueueRequestorExample
To run the example, simply type mvn verify -Pexample
from this directory
client-jndi.properties
file in the directory ../common/config
InitialContext initialContext = getContext();
Queue queue = (Queue)initialContext.lookup("/queue/exampleQueue");
QueueConnectionFactory cf = (QueueConnectionFactory)initialContext.lookup("/ConnectionFactory");
TextReverserService reverserService = new TextReverserService(cf, queue);
connection = cf.createQueueConnection();
connection.start();
QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
QueueRequestor queueRequestor = new QueueRequestor(session, queue);
TextMessage request = session.createTextMessage("Hello, World!");
We use the queue requestor to send the request and block until a reply is received.
Using the queue requestor simplify request/reply use case by abstracting boilerplate JMS code
(creating a temporary queue, a consumer and a producer, setting the JMS ReplyTo header on the request,
sending the request with the producer, consuming the message from the consumer).
All this code is replaced by a single call to QueueRequestor.request()
method.
TextMessage reply = (TextMessage)queueRequestor.request(request);
System.out.println("Send request: " + request.getText());
System.out.println("Received reply:" + reply.getText());
queueRequestor.close()
reverserService.close()
finally
block. Closing a JMS connection will automatically close all of its sessions, consumers, producer and browser objects
finally
{
if (initialContext != null)
{
initialContext.close();
}
if (connection != null)
{
connection.close();
}
}