如何将 jms 消息发送到 activeMQ 并使用 mqttJS 在 javascript 中正确解码

How to send a jms message to activeMQ and decode it in javascript with mqttJS properly

我有一个 java 后端,我可以在其中通过

向主题发送消息
jmsTemplate.convertAndSend("topic", "Hello World!");

在我的 java 脚本前端中,我使用 mqttJS 连接到 activeMQ 并接收消息:

    let mqtt = require('mqtt')
    let options ={
        clientId:"test",
        username:"username",
        useSSL: true,
        password:"password",
        clean:true};
    let client  = mqtt.connect(
        'wss://someUrl.com:61619',
        options);

    client.on('connect', function () {
        client.subscribe('myTopic', function (err) {
            if (!err) {
                console.log("successfully connected to myTopic'");
            }
        })
    });

    client.on('message', function (topic, message) {
        console.log(message.toString());
    });

我从后端收到的消息是这样的:

S�A S�)�x-opt-jms-destQ�x-opt-jms-msg-typeQ Ss�   f    
�/ID:myID@�topic://myTopic@@@@�  j��< St�
e Sw�  Hello World!

我的消息 "Hello World!" 在那里。还要一堆看不懂的进去,我估计离了header。

我在后端尝试了不同的 MessageConverters,在前端尝试了不同的解析器。没有任何效果。

我需要做什么才能得到 "Hello World!" 作为消息?或者有没有更好的方法发送消息,使用jms,这是必需的。

如果你正在使用 mqtt 3.0.0 你应该添加额外的参数:

If you are connecting to a broker that supports only MQTT 3.1 (not 3.1.1 compliant), you should pass these additional options:

{
   protocolId: 'MQIsdp',
   protocolVersion: 3
 }

更新:

切换到 ActiveMQ Artemis 后,支持 JMS 2,无需任何正则表达式即可完美运行。

旧post:

因为我没有找到任何解决方案来过滤消息的 body 或发送没有 header 的消息(相关的,未回答的问题在这里:How to send plain text JmsMessage with empty header)解决方案是发送 JSON object 并使用正则表达式在前端过滤 JSON 语法。

后端:

private void sendHelloWorld() {
    Map<String, String> subPayload = new HashMap<>();
    subPayload.put("test1", "value2");
    subPayload.put("test2", "value3");
    Map<String, Object> payload = new HashMap<>();
    payload.put("message", "Hello World!");
    payload.put("context", "Something");
    payload.put("map", subPayload);
    jmsTemplate.setMessageConverter(new MappingJackson2MessageConverter());
    jmsTemplate.convertAndSend( "notification/prediction", payload );
}

前端:

client.on('message', function (topic, message, packet) {
    const regex = /\{(.*)\}$/g;
    const match = message.toString().match(regex);
    if(null === match) {
        console.error("Could not parse message");
        console.log('message', message.toString());
    }
    const json = JSON.parse(match[0]);
    console.log('message', json);
});

结果将是:

{
  "message":"Hello World!", 
  "context":"Something",
  "map": {
     "test1":"value2",
     "test2":"value3"
   }
}