Spring Integration(MQTT):检索已发布的消息

时间:2019-02-01 06:27:31

标签: java spring spring-boot mqtt

我是Spring Boot的新手,我正在尝试使用spring集成中的示例示例,以便使用MQTT进行订阅和发布。我设法将它与Thingsboard集成在一起,并且下面的代码中的记录器能够从Thingsboard接收已发布的消息。

public static void main(String[] args) {
    SpringApplication.run(MqttTest.class);
}

@Bean
public MqttPahoClientFactory mqttClientFactory() {
    DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
    MqttConnectOptions options = new MqttConnectOptions();
    options.setServerURIs(new String[] { "URI HERE" });
    options.setUserName("ACCESS TOKEN HERE");
    factory.setConnectionOptions(options);
    return factory;
}

// consumer

@Bean
public IntegrationFlow mqttInFlow() {
    return IntegrationFlows.from(mqttInbound())
            .transform(p -> p)
            .handle(logger())
            .get();
}

private LoggingHandler logger() {
    LoggingHandler loggingHandler = new LoggingHandler("INFO");
    loggingHandler.setLoggerName("LoggerBot");
    return loggingHandler;
}

@Bean
public MessageProducerSupport mqttInbound() {
    MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter("Consumer",
            mqttClientFactory(), "v1/devices/me/rpc/request/+");
    adapter.setCompletionTimeout(5000);
    adapter.setConverter(new DefaultPahoMessageConverter());
    adapter.setQos(1);
    return adapter;
}

这是控制台输出。我能够接收从Thingsboard仪表板发送的已发布json消息。我想知道是否有一个调用方法来检索json消息字符串,以便我可以进一步处理它。谢谢。

2019-02-01 14:06:23.590  INFO 13416 --- [ Call: Consumer] LoggerBot : {"method":"setValue","params":true}
2019-02-01 14:06:24.840  INFO 13416 --- [ Call: Consumer] LoggerBot : {"method":"setValue","params":false}

1 个答案:

答案 0 :(得分:1)

要处理已发布的消息,请订阅消息句柄以使用消息流。

MessageHandler

    @Bean
    public IntegrationFlow mqttInFlow() {
        return IntegrationFlows.from(mqttInbound())
                .transform(p -> p)
                .handle( mess -> {
                   System.out.println("mess"+mess);
                 })            
                .get();
    }

ServiceActivator


    @Bean
    public IntegrationFlow mqttInFlow() {
        return IntegrationFlows.from(mqttInbound())
                .transform(p -> p)
                .handle("myService","handleHere")
                .handle(logger())
                .get();
    }

@Component
public class MyService {

    @ServiceActivator
    public Object handleHere(@Payload Object mess) {
        System.out.println("payload "+mess);
        return mess;
    }
}

注意:正如我们所讨论的,实现它有很多不同的方法。 这只是您理解的示例。