1

配置

@Configuration
@IntegrationComponentScan
public class MqttV5ChannelConfig {
    @Bean
    public MqttConnectionOptions getMqttConnectionOptions() throws Exception {
        MqttConnectionOptions options = new MqttConnectionOptions();
        options.setUserName(xxx);
        options.setPassword(xxx);
        options.setServerURIs(xxx);
        options.setAutomaticReconnect(true);
        options.setCleanStart(false);
    }
    @Bean
    public MessageProducer inbound(MqttConnectionOptions options) {
        Mqttv5PahoMessageDrivenChannelAdapter adapter = new Mqttv5PahoMessageDrivenChannelAdapter(options, "Client_" + System.currentTimeMillis(), "test");
        adapter.setCompletionTimeout(5000);
        adapter.setQos(0);
        adapter.setOutputChannel(mqttInboundChannel());
        adapter.setErrorChannel(errorChannel());
        return adapter;
    }
    @Bean
    @ServiceActivator(inputChannel = "mqttOutboundChannel")
    public MessageHandler mqttOutbound(MqttConnectionOptions options) {
        Mqttv5PahoMessageHandler handler = new Mqttv5PahoMessageHandler(options, "Client_" + System.currentTimeMillis());
        handler.setAsync(true);
        handler.setDefaultTopic("test");
        return handler;
    }
    @Bean
    public MessageChannel mqttOutboundChannel(){
        return new DirectChannel();
    }
    @Bean
    public MessageChannel mqttInboundChannel(){
        return new DirectChannel();
    }
    @Bean
    public MessageChannel errorChannel(){
        return new DirectChannel();
    }
}

错误日志

org.springframework.context.ApplicationContextException: Failed to start bean 'mqttV5ChannelConfig.mqttOutbound.serviceActivator'; nested exception is java.lang.IllegalStateException: Cannot connect 'MqttAsyncClient' for: mqttOutbound
    at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181)
    at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54)
    at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356)

问题

我希望网络断开时启动不会失败。当网络连接或我推送消息时,它将自动重新连接。

我该如何配置?

4

1 回答 1

0

inboundbean 中,adapter.setAutoStartup(false)将阻止上下文在初始化期间启动适配器。

然后,您可以start()手动适配器(大概在 try/catch 块中)。

于 2021-12-16T14:25:45.177 回答