使用spring集成将字符串从mqtt转换为对象

oug3syen  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(403)

我想将从mqtt servet接收到的消息转换为java对象。我找不到一个关于如何使用spring集成工具的提示。这是密码

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

下面是处理程序的代码

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

  }
}

我认为这是可能的,因为使用springjms是可能的。设置jms连接的方法非常相似。

w41d8nur

w41d8nur1#

这个 DefaultPahoMessageConverter 可提供任何 BytesMessageMapper ,其中一个在那里 ConvertingBytesMessageMapper . 反过来,你可以提供任何 MessageConverter 实施,例如。 MappingJackson2MessageConverter .

相关问题