kakaka
kakaka

Reputation: 37

MQTT shared subscription

With a MQTT shared subscription, the message on the subscirbed topic would only be sent to one of the subscribing clients. Then, how the other clients of the group receive the message as they also subscribe to the same topic?

Upvotes: 1

Views: 2457

Answers (2)

MAGx2
MAGx2

Reputation: 3189

There is an interesting bug in Java Paho (1.2.5) client that prevents working with shared topics that contains wildcards (#, +) https://github.com/eclipse/paho.mqtt.java/issues/827

Long story short, this will not work:

mqttClient.subscribe("$share/group/some_topic/#", 1, (topic, message) -> System.out.println(topic));

instead it's required to use callbacks:

mqttClient.subscribe("$share/group/some_topic/#", 1);
mqttClient.setCallback(new MqttCallback() {
    @Override
    public void connectionLost(final Throwable cause) {

    }

    @Override
    public void messageArrived(final String topic, final MqttMessage message) throws Exception {
        System.out.println(topic);
    }

    @Override
    public void deliveryComplete(final IMqttDeliveryToken token) {

    }
});

Upvotes: 2

Brits
Brits

Reputation: 18315

With a MQTT shared subscription, the message on the subscribed topic would only be sent to one of the subscribing clients.

Correct. With a normal (non‑shared) subscription the messages are sent to ALL subscribers; with shared subscriptions they are sent to ONE subscriber.

Prior to the introduction of shared subscriptions it was difficult to handle situations where you want multiple servers (for fault tolerance, load balancing etc) but only want to process each message once. Shared subscriptions provide a simple way of accomplishing this.

Then, how the other clients of the group receive the message as they also subscribe to the same topic?

If they are subscribing to the same shared subscription (with the same ShareName) then only one will receive the message; this is by design. If you want them all to receive the message then don't use a shared subscription. Alternatively you can establish multiple subscriptions (so all subscribers receive the message but only one processes it - but note the "could") as per the spec:

If a Client has a Shared Subscription and a Non‑shared Subscription and a message matches both of them, the Client will receive a copy of the message by virtue of it having the Non‑shared Subscription. A second copy of the message will be delivered to one of the subscribers to the Shared Subscription, and this could result in a second copy being sent to this Client.

Upvotes: 3

Related Questions