I want to convert received message from mqtt-servet to an java object. I couldn't find a hint how it is possible with spring-integration tools. Here is the code
@Bean
public MqttPahoClientFactory mqttClientFactory() {
DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
MqttConnectOptions options = new MqttConnectOptions();
options.setServerURIs(new String[]
{
"ssl://"+this.hostname+":"+this.port,
}
);
options.setUserName(this.username);
options.setPassword(this.password.toCharArray());
factory.setConnectionOptions(options);
return factory;
}
@Bean
public MessageProducer inboundSendorData() {
String clientId = "Java_" + UUID.randomUUID().toString();
MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(
clientId,
this.mqttClientFactory(),
"sensordata"
);
//DefaultPahoMessageConverter converter = new DefaultPahoMessageConverter();
//adapter.setConverter(converter);
adapter.setCompletionTimeout(5000);
adapter.setConverter(new DefaultPahoMessageConverter());
adapter.setQos(1);
adapter.setOutputChannel(mqttInputChannelSensorData());
return adapter;
}
@Bean
public MessageChannel mqttInputChannelSensorData() {
return new DirectChannel();
}
@Bean
@ServiceActivator(inputChannel = "mqttInputChannelSensorData")
public MessageHandler handlerSensorData() {
return new MqttSubSensorHandler();
}
Here is the code for the Handler
public class MqttSubSensorHandler implements MessageHandler {
@Autowired
private SensorRepository sensorRepository;
@Autowired
public MqttSubSensorHandler(SensorRepository sensorRepository) {
this.sensorRepository = sensorRepository;
}
public MqttSubSensorHandler() {
}
public void handleResponse(Message<?> message) {
}
@Override
public void handleMessage(Message<?> message) throws MessagingException {
System.out.println(message.getPayload());
}
}
I assume it is possible, because it is possible with Spring JMS. And the approach for setting up the JMS connection is pretty similar.
question from:
https://stackoverflow.com/questions/65941510/convert-string-from-mqtt-to-object-with-spring-integration 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…