Topic wildcards

Overview

In MQTT, wildcards provide a powerful mechanism for subscribing to multiple topics simultaneously. When a client subscribes to a topic, it can either subscribe to the exact topic of a published message or utilise wildcards to broaden its subscription.

How are wildcards used?

  • Clients can subscribe to a wildcard topic to receive messages from multiple matching topics.

  • Wildcards can reduce overhead by eliminating the need to subscribe to each topic individually.

  • Wildcards are used when there is uncertainty about the topics that publishing clients will use.

Single level wildcard

Taking advantage of MQTT wildcard capabilities is through the use of a custom event parser. This section will walk you through the process.

Example

Events will be received from various rooms within a house using the follow example topic structure:

sensors/kitchen/temperaturehumidity
sensors/livingroom/temperaturehumidity
sensors/hallway/temperaturehumidity
sensors/bedroom1/temperaturehumidity
sensors/bedroom2/temperaturehumidity

And the subscription will use the single level wildcard method '+':

sensors/+/temperaturehumidity

We shall use the '+' MQTT wildcard to recieve all sensor data from each connected room.

mqttConsumer:
  broker: tcp://127.0.0.1:1883
  topic: sensors/groundfloor/+/temperaturehumidity

  clientId: tempHumidyManagementProcessor
  qos: 1

  deserializer:
    parser: com.fractalworks.mqtt.example.TemperatureHumiditySensorParser
    compressed: false
    batch: false

Multi level wildcard

Nothing really changes much when using this wildcard except that you may want to change how you parse the topic string.

Example

This example would now receive all sensor information from a house. The parser would need to coded such that events can be handled holistically within the target stream processor

// Some code
mqttConsumer:
  broker: tcp://127.0.0.1:1883
  topic: sensors/#

  clientId: tempHumidyManagementProcessor
  qos: 1

  deserializer:
    parser: com.fractalworks.mqtt.example.TemperatureHumiditySensorParser
    compressed: false
    batch: false

Notes

See the great documentation HiveMQ has produced that covers this subject.

Last updated

Was this helpful?