0

我使用以下示例作为我自己的代码发布到 MQTT 服务器的基础:https ://github.com/spring-projects/spring-integration-samples/blob/master/basic/mqtt/src/main/ java/org/springframework/integration/samples/mqtt/Application.java

我有一个特殊的用例,其中密码是一个令牌,特别是一个会过期的 keycloak 令牌。如果出于某种原因,spring 应用程序失去与 MQTT 服务器的连接并尝试重新连接,则令牌将过期,并且将抛出 MqttSecurityException: Not authorized to connect 异常。我尝试在 MqttPahoMessageHandler 中扩展 connectionLost 方法,但由于 MqttPahoClientFactory 和 IMqttAsyncClient 是私有的 final,所以我无能为力。想知道是否还有其他我没有想到的方法,或者图书馆只是不打算像这样使用???

感谢您的任何回复。

4

1 回答 1

0

每次尝试连接时,我们都会MqttConnectOptions从客户端工厂获取密码,因此您应该可以在那里更新密码。

如果由于某种原因这不起作用,请打开一个新功能请求

编辑

关于你的评论,这有什么问题?

    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions options = new MqttConnectOptions();
        options.setServerURIs(new String[] { "tcp://localhost:1883" });
        options.setUserName("guest");
        options.setPassword("guest".toCharArray());
        factory.setConnectionOptions(options);
        return factory;
    }

    @Bean
    public ApplicationRunner runner(MqttPahoClientFactory mqttClientFactory, MqttPahoMessageHandler handler) {
        return args -> {
            Thread.sleep(30_000);
            System.out.println("Changing password");
            mqttClientFactory.getConnectionOptions().setPassword("foo".toCharArray());
            handler.stop();
            handler.start();
        };
    }
foo
2020-03-10 17:42:33.560  INFO 95638 --- [iSampleConsumer] siSample                                 
  : foo sent to MQTT, received from MQTT
Changing password
foo
2020-03-10 17:43:08.705 ERROR 95638 --- [ask-scheduler-3] o.s.integration.handler.LoggingHandler   
  : org.springframework.messaging.MessageHandlingException: error occurred in message handler [bean 'mqttOutbound' for component 'mqttOutFlow.org.springframework.integration.config.ConsumerEndpointFactoryBean#1'; defined in: 'com.example.demo.So60610337Application'; from source: 'org.springframework.core.type.StandardMethodMetadata@79da8dc5']; nested exception is org.springframework.messaging.MessagingException: Failed to connect; nested exception is Bad user name or password (4), failedMessage=GenericMessage [payload=foo sent to MQTT, headers={id=4eab5b52-726f-7ea3-252d-77c4d0401cc8, timestamp=1583876588662}]
...
Caused by: Bad user name or password (4)
于 2020-03-10T03:20:40.860 回答