Skip to content
Advertisement

Multi MQTT clients subscribed to the same topic

I have actually a spring boot application with a MQTT client into it that is subscribed to topic.

I encounter a problem when i put 2 instances of my application ( 2 containers/pods ) because it creates 2 connections to the publisher ! The problem is that I record things in a database for each message, so I receive the data 2 times ! One from a pod, and one from the second one..and so 2 record in database…

This is my actual code :

.
..
...
....
    @Bean
    public MqttConnectOptions getReceiverMqttConnectOptions() {
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setCleanSession(true);
        mqttConnectOptions.setConnectionTimeout(30);
        mqttConnectOptions.setKeepAliveInterval(60);
        mqttConnectOptions.setAutomaticReconnect(true);

        mqttConnectOptions.setUserName(bean.getProperty("username"));
        String password = bean.getProperty("password");
        String hostUrl = bean.getProperty("url");

        mqttConnectOptions.setPassword(password.toCharArray());
        mqttConnectOptions.setServerURIs(new String[] { hostUrl });
        return mqttConnectOptions;
    }

    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        factory.setConnectionOptions(getReceiverMqttConnectOptions());
        return factory;
    }

    @Bean
    public MessageChannel mqttInputChannel() {
        return new DirectChannel();
    }

    @Bean
    public MessageProducer inbound() {
        String clientId = "client-id" + UUID.randomUUID().toString();
        MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(clientId, mqttClientFactory(), "jenkins");
        adapter.setCompletionTimeout(20000);
        adapter.setConverter(new DefaultPahoMessageConverter());
...
..
.

If any of you have a solution to be able to use 2 pod of my application without creating 2 MQTT connection.. Thanks

Advertisement

Answer

You need to use a broker that supports Shared Subscriptions (this is feature added to MQTTv5 standard, but some brokers supported none standard versions at v3)

Shared Subscriptions allow groups of clients to subscribe to the a topic (or wildcard topic) and any given message published to that topic will only be delivered to one of the group of clients.

You can read more about Shared Subscriptions here

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement