如何将 headers 发送到 JMS 消息

How to send headers to a JMS message

我正在尝试将 headers 添加到 JMS 消息中。 headers 为 eventTypemessageIdcorrelationIdmessageStamp。这是我的 queue 发件人方法:

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();
        }
    }
}

如何将 headers 与负载一起发送?

由于您使用的是 JMS,因此方法是消息属性。您使用 setXxxProperty 系列方法定义它们。引用自 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.

所以,继续,创建您的消息,例如:TextMessage textMessage = session.createTextMessage(payload); 然后将 headers 设置为:

textMessage.setStringProperty("name", "value");
textMessage.setBooleanProperty("i_am_a_header", true);
// etc