Message Correlation
In the previous code example, the borrower sent a loan request on a request queue and waited for a reply from the lender on a response queue. Many borrowers may be making requests at the same time, meaning that the lender application is sending many messages to the response queue. Since the response queue may contain many messages, how can you be sure that the response you received from the lender was meant for you and not another borrower?
In general, whenever using the request/reply model, you must make
sure the response you are receiving is associated with the original
message you sent. Message correlation is the
technique used to ensure that you receive the right message. The most
popular method for correlating messages is leveraging the JMSCorrelationID message header property in
conjunction with the JMSMessageID
header property. The JMSCorrelationID
property contains a unique String
value that is known by both the sender and receiver. The JMSMessageID is typically used, since it is
unique and is available to the sender and receiver.
When the message consumer (e.g., QLender) is ready to send the reply message,
it sets the JMSCorrelationID message
property to the message ID from the original message:
public class QLender implements MessageListener {
...
public void onMessage(Message message) {
try {
...
// Send the results back to the borrower
TextMessage tmsg = qSession.createTextMessage();
tmsg.setText(accepted ? "Accepted!" : "Declined");
tmsg.setJMSCorrelationID(message.getJMSMessageID()); ...