How to make a JMS Synchronous request

rk2010 picture rk2010 · May 28, 2012 · Viewed 15.8k times · Source

I have an webapp that is expected to fetch and display data from an External App which is accessible only via messaging (JMS).

So, if a user submits a request on a browser, the same HTTP request thread will have to interact with the Messaging system (MQ Series) such that the same request thread can display the data received from the Messaging System.

Is there a pattern I can make use of here? I saw some vague references on the net that use "Correlation ID" in this way:

Msg m = new TextMsg("findDataXYZ");
String cr_id = m.setCorrelationID(id);

sendQueue.send(m).

// now start listening to the Queue for a msg that bears that specific cr_id

Response r = receiverQueue.receive(cr_id);

Is there something better out there? The other patterns I found expect the response to be received asynchronously.. which is not an option for me, since I have to send the response back on the same HTTP request.

Answer

Shashi picture Shashi · May 28, 2012

The request/reply messaging pattern is useful for your requirement. You typically use a CorrelationId to relate request & reply messages.

While sending request message you set JMSReplyTo destination on the message. Typically a temporary queue is used as JMSReplyTo destination. When creating a consumer to receive response use a selector with JMSCorrelationId, something like

cons = session.createConsumer(tempDestination,"JMSCorrelationId="+requestMsg.JMSMessageId);

At the other end, the application that is processing the request message must use the JMSReplyTo destination to send response. It must also use the MessageId of the request message and set it as CorrelationId of the response message.