如何在收到弹簧mqtt集成时停止重复订阅保留的消息

问题描述 投票:0回答:1

在订阅保留主题时获取重复保留的消息。

我在我的Iot项目中使用了spring mqtt集成。这里一旦收到保留的消息,它将继续订阅,直到我将空白消息发布到同一主题,并将保留标志设置为true。我注意到,当我使用mqtt命令在终端中执行相同的过程,例如订阅保留的主题时,它只订阅一次,不会重复订阅。

我使用以下代码通过使用#订阅所有主题

@Bean
    public MessageChannel mqttInputChannel() {
        return new DirectChannel();
    }
    @Bean
    public DefaultMqttPahoClientFactory clientfactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName("username");
        options.setPassword("password".toCharArray());
        options.setCleanSession(false);
        //options.setCleanSession(true);
        //options.setServerURIs(new String[] { "tcp://localhost" });
        options.setServerURIs(new String[] { "url" });
        factory.setConnectionOptions(options);
        return factory;
    }

    @Bean
    public MqttPahoMessageDrivenChannelAdapter inbound() {

        MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter("admin",
                clientfactory(), "#");
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setQos(1);
        adapter.setOutputChannel(mqttInputChannel());
        /*adapter.setc*/
        return adapter;
    }

    @Bean
    @ServiceActivator(inputChannel = "mqttInputChannel")

    public MessageHandler handler() {
        return new MessageHandler() {

            public void handleMessage(Message<?> message) throws MessagingException {

            mqttSubscriptionProcessor.processSubscription(message);


            }

        };
    }

我使用此命令发布了保留的消息

mosquitto_pub -u admin -P pwd -t hello/topic  -m "test msg" -r -d

和eclipse控制台的结果是

{mqtt_receivedRetained=true, id=48afaec5-debf-4927-ce06-a80556e479ac, mqtt_duplicate=false, mqtt_receivedTopic=hello/topic, mqtt_receivedQos=0, timestamp=1554363853214}
test msg

{mqtt_receivedRetained=true, id=48afaec5-debf-4927-ce06-a80556e479ac, mqtt_duplicate=false, mqtt_receivedTopic=hello/topic, mqtt_receivedQos=0, timestamp=1554363853214}
test msg

{mqtt_receivedRetained=true, id=48afaec5-debf-4927-ce06-a80556e479ac, mqtt_duplicate=false, mqtt_receivedTopic=hello/topic, mqtt_receivedQos=0, timestamp=1554363853214}
test msg 

{mqtt_receivedRetained=true, id=48afaec5-debf-4927-ce06-a80556e479ac, mqtt_duplicate=false, mqtt_receivedTopic=hello/topic, mqtt_receivedQos=0, timestamp=1554363853214}
test msg

在这里,我只需要保留一次保留的主题,必须更改spring集成代码中的任何更改。

java spring spring-integration mqtt mosquitto
1个回答
1
投票

这就是保留消息的工作方式,在保留位设置为主题时发布的最后一条消息将始终在任何新消息之前订阅匹配主题时首先传递给客户端。

如果您不希望保留该消息(并且始终如此保留),则在发布时不要设置保留位。

否则,您已发现可以通过发布具有空有效负载的消息并将保留位设置为同一主题来清除主题的保留消息。

或者您可以过滤客户端中的消息,因为您始终可以检查消息在传递时是否设置了保留标志。

至于弹簧方面,看起来你正在创建4个客户端,因此每个客户端都在订阅时收到消息。您可以通过查看代理日志来证明这一点,如果您在详细模式下运行mosquitto,它将显示它传递的每条消息。

© www.soinside.com 2019 - 2024. All rights reserved.