使用 Spring Integration 下的 Paho 接收二进制 MQTT 消息
Use Paho under Spring Integration to receive binary MQTT message
我有这段代码可以在 Spring Integration 5.0.x / Boot 2.0 下接收 MQTT 消息。它适用于文本消息,但当我尝试处理二进制消息时,它失败了,因为发生了到 String
的转换,这会破坏内容(在本例中为 png 图像文件)。
我怎样才能收到未被篡改的消息?
我尝试在 DefaultPahoMessageConverter
上 setBytesMessageMapper
,但这并没有改变任何事情。
当我使用 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();
...
};
}
将转换器上的 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;
}
我有这段代码可以在 Spring Integration 5.0.x / Boot 2.0 下接收 MQTT 消息。它适用于文本消息,但当我尝试处理二进制消息时,它失败了,因为发生了到 String
的转换,这会破坏内容(在本例中为 png 图像文件)。
我怎样才能收到未被篡改的消息?
我尝试在 DefaultPahoMessageConverter
上 setBytesMessageMapper
,但这并没有改变任何事情。
当我使用 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();
...
};
}
将转换器上的 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;
}