JMSCorrelationID — Purpose: Routing
The
JMSCorrelationID
provides a header for associating the
current message with some previous message
or application-specific ID. In most cases, the
JMSCorrelationID
will be used to tag a message as
a reply to a previous message. The following code shows how the
JMSCorrelationID
is set and used along with the
JMSReplyTo
and JMSMessageID
headers to send a reply to a message:
public void onMessage(Message message){
try {
TextMessage textMessage = (TextMessage)message;
Topic replyTopic = (Topic)textMessage.getJMSReplyTo( );
Message replyMessage = session.createMessage( );
String messageID = textMessage.getJMSMessageID( );
replyMessage.setJMSCorrelationID(messageID);
publisher.publish(replyTopic, replyMessage);
} catch (JMSException jmse){jmse.printStackTrace( );}
}
When the JMS client receives the reply message, it can match the
JMSCorrelationID
of the new message with the
corresponding JMSMessageID
of the message it sent,
so that it knows which message received a reply. The
JMSCorrelationID
can be any value, not just a
JMSMessageID
. The
JMSCorrelationID
header is often used with
application-specific identifiers. Our example in Chapter 4 uses the JMSCorrelationID
as a way of identifying the sender. The important thing to remember,
however, is that the JMSCorrelationID
does not
have to be a JMSMessageID
, although it frequently
is. If you decide to use your own ID, be aware that an
application-specific JMSCorrelationID
must not
start with ID:
. That prefix is reserved for ID
generated by JMS providers.
The methods for accessing and mutating the
JMSCorrelationID
come in two forms: a
String
form and an AsBytes
form. The String
-based header is the most common
and must be supported by JMS providers. The
AsBytes
method, which is based on a byte array, is
an optional feature that JMS providers do not have to support.
It's used for setting the JMSCorrelationID
to some native JMS provider correlation ID:
Message message = topicSession.createMessage( );
byte [] byteArray = ... set to some JMS specific byte array
...
message.setJMSCorrelationIDAsBytes(byteArray);
publisher.publish(message);
If the JMS provider supports messaging exchanges with a legacy
messaging system that uses a native form of the correlation ID, the
AsBytes
method will be useful. If the
AsBytes
form is not supported,
setJMSCorrelationIDAsBytes( )
throws a
java.lang.UnsupportedOperationException.