在Spring Integration下使用Paho来接收二进制MQTT消息

时间:2018-03-29 18:19:41

标签: java spring-integration mqtt paho spring-integration-mqtt

我有这个代码在Spring Integration 5.0.x / Boot 2.0下接收MQTT消息。它适用于文本消息,但是当我尝试处理二进制消息时,它会失败,因为转换到String会发生这种情况,这会破坏内容(在这种情况下:png图像文件)。

如何收到未被取消的邮件?

我尝试setBytesMessageMapper DefaultPahoMessageConverter,但这并没有改变一件事。 当我使用mqtt.fx下载消息内容时,我可以证明二进制内容设置正确,所以我确信这是接收端的问题。

@Bean
public MessageProducer inbound() {
    MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter("tcp://iot.eclipse.org:1883",
                "foo", "bar");
    adapter.setCompletionTimeout(5000);
    DefaultPahoMessageConverter converter = new DefaultPahoMessageConverter();
    adapter.setConverter(converter);
    adapter.setQos(1);
    adapter.setOutputChannel(mqttInputChannel());
    return adapter;
}
...
@Bean
@ServiceActivator(inputChannel = "mqttInputChannel")
public MessageHandler handler() {
    return new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            System.out.println("message received on " + new Date());        
            Object payload = message.getPayload();
            ...
    };
}

1 个答案:

答案 0 :(得分:2)

将转换器上的payloadAsBytes属性设置为true ...

/**
 * True if the converter should not convert the message payload to a String.
 * Ignored if a {@link BytesMessageMapper} is provided.
 *
 * @param payloadAsBytes The payloadAsBytes to set.
 * @see #setBytesMessageMapper(BytesMessageMapper)
 */
public void setPayloadAsBytes(boolean payloadAsBytes) {
    this.payloadAsBytes = payloadAsBytes;
}