How to send a response to a message (Request/Reply)
In messaging systems it is not that common that the receiver of a message sends a response, but it is possible and JMS supports this with the JMSReplyTo and JMSCorrelationID header fields. Often temporary queues are used to send the reply, but you can also use a regular queue.
The following snippet sends a message, creates a temporary queue for the response and then waits for it:
Session session = ...;
Queue queue = ...;
MessageProducer producer = session.createProducer(queue);
Queue tmpQueue = session.createTemporaryQueue();
MessageConsumer consumer = session.createConsumer(tmpQueue);
// Send request
Message request = session.createTextMessage("how are you?");
request.setJMSReplyTo(tmpQueue);
producer.send(request);
// Wait for response
Message reply = consumer.receive();
TextMessage tm = (TextMessage) reply;
System.out.println("Got reply: " + tm.getText());
This snippet shows how to respond to messages:
Connection con = ...;
Session session = ...;
Queue queue = ...;
MessageConsumer consumer = session.createConsumer(queue);
MessageProducer producer = session.createProducer(null); // no default queue (more)
con.start();
while (true) {
Message request = consumer.receive();
TextMessage tm = (TextMessage) request;
System.out.println("Got request: " + tm.getText());
TextMessage reply = session.createTextMessage("great");
reply.setJMSCorrelationID(request.getJMSMessageID()); // link messages (more)
producer.send(request.getJMSReplyTo(), reply); // send reply over temporary queue
}