How to send headers to a JMS message
I am trying to add headers to a JMS message. The headers being eventType
, messageId
, correlationId
and messageStamp
. This is my queue sender method:
public void messageSentInQueue(String queueName, Message payload)
throws JMSException {
if (!MessageQueueConfigs.userName.isEmpty() || !MessageQueueConfigs.password.isEmpty() || !MessageQueueConfigs.brokerUrl.isEmpty()) {
try {
connection = ActiveMQConnection.makeConnection(MessageQueueConfigs.userName, MessageQueueConfigs.password, MessageQueueConfigs.brokerUrl);
connection.start();
// create a Session
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
System.out.print("what is session" + session);
// create the Queue to which messages will be sent . If the Queue is not there it will be auto created
Queue queue = session.createQueue(queueName);
// create a MessageProducer for sending messages
messageProducer = session.createProducer(queue);
TextMessage textMessage = session.createTextMessage(payload);
System.out.println("message to sent" + payload);
messageProducer.send(payload);
} catch (Exception e) {
e.printStackTrace();
} finally {
connection.close();
}
}
}
How can I send headers along with the payload?
Solution 1:
Since you are using JMS, the way to go is the message properties. You define them with the setXxxProperty
family of methods. Quoting from the Message Javadocs:
Message Properties
A Message object contains a built-in facility for supporting application-defined property values. In effect, this provides a mechanism for adding application-specific header fields to a message.
So, go ahead, create your message, e.g.: TextMessage textMessage = session.createTextMessage(payload);
and then set headers as:
textMessage.setStringProperty("name", "value");
textMessage.setBooleanProperty("i_am_a_header", true);
// etc