Exclusive Subscription

Exclusive subscription is an extended MQTT feature supported by EMQX. It allows mutually exclusive subscriptions to topics. Only one subscriber is allowed to subscribe to a topic at a time. Other subscribers will not be able to subscribe to the corresponding topic until the current subscriber unsubscribe from the subscription.

To make a subscription exclusive, you need to add a prefix to the topic heading. The table below shows an example:

ExamplePrefixReal Topic Name
$exclusive/t/1$exclusive/t/1

When client A subscribes to $exclusive/t/1, other clients will fail to subscribe to $exclusive/t/1 until A cancels the subscription to $exclusive/t/1.

Note

Exclusive subscriptions must be prefixed with $exclusive/, in the above example, other clients can still successfully subscribe via t/1.

Configure Exclusive Subscription via Configuration File

The exclusive subscription is disabled by default. You can enable this feature in etc/emqx.conf.

Note

Configuration using the Dashboard is currently not supported.

  1. mqtt.exclusive_subscription {
  2. enable = true
  3. }

Try Exclusive Subscription with MQTTX Client

Prerequisites

  • Basic publishing and subscribing operations using MQTTX Client
  • Exclusive subscription is enabled.
  1. Start the MQTTX Client. Click the New Connection to create an MQTT connection named Demo.

    • The localhost 127.0.0.1 is used as an example in this demonstration.

    TIP

    For detailed instructions on creating an MQTT connection, see MQTTX Client.

    Configure-new-connection-general

  2. Create another 2 MQTT connections. Configure them as Subscriber1 and Subscriber2 respectively.

  3. Select the connection named Subscriber1 in the Connections pane. Click the New Subscription button to create a subscription. Type $exclusive/t/1 in the Topic text box to subscribe to this topic. Click Confirm.

    subscribe-exclusive-topic

  4. Select the connection named Subscriber2 in the Connections pane. Click the New Subscription button to create a subscription. Type $exclusive/t/1 in the Topic text box to subscribe to this topic. Click Confirm.

    • An error message pops up.

    fail-to-exclusive-subscription

Try Exclusive Subscription with MQTTX CLI

Prerequisites

  • Basic publishing and subscribing operations using MQTTX CLI
  • Exclusive subscription is enabled.
  1. Use the following command to make an exclusive subscribscription.

    1. mqttx sub -t "$exclusive/t/1"
  2. Use the command in step 1 again to make another subscription to the topic $exclusive/t/1. It will return:

    1. subscription negated to t/2 with code 135

    Subscription Error Code:

    CodeReason
    0x8FUse $exclusive/ without exclusive subscription enabled
    0x97A client has already subscribed to this topic