乐闻世界logo
搜索文章和话题

What are MQTT's topic wildcards? How to use them?

2月21日 15:45

MQTT topic wildcards are a powerful subscription mechanism that allows clients to subscribe to a category of topics rather than a single topic, improving subscription flexibility.

Types of Topic Wildcards

MQTT provides two types of wildcards:

1. Single-level Wildcard (+)

  • Symbol: Plus sign (+)
  • Purpose: Matches a single level in the topic
  • Position: Can appear anywhere in the topic
  • Limitation: Cannot match empty levels

2. Multi-level Wildcard (#)

  • Symbol: Hash sign (#)
  • Purpose: Matches multiple levels in the topic (including zero)
  • Position: Must appear at the end of the topic
  • Limitation: Must be the last character in the topic filter

Wildcard Usage Examples

Single-level Wildcard (+) Examples

shell
Subscription: home/+/temperature Matching topics: - home/livingroom/temperature ✓ - home/bedroom/temperature ✓ - home/kitchen/temperature ✓ Non-matching topics: - home/livingroom/kitchen/temperature ✗ (too many levels) - home/temperature ✗ (too few levels) - home/livingroom/humidity ✗ (last level doesn't match)
shell
Subscription: sensor/+/data/+ Matching topics: - sensor/001/data/temperature ✓ - sensor/002/data/humidity ✓ - sensor/003/data/pressure ✓ Non-matching topics: - sensor/001/data ✗ (too few levels) - sensor/001/data/temperature/value ✗ (too many levels)

Multi-level Wildcard (#) Examples

shell
Subscription: home/# Matching topics: - home/ ✓ - home/livingroom ✓ - home/livingroom/temperature ✓ - home/livingroom/temperature/value ✓ - home/bedroom/humidity ✓ Non-matching topics: - home ✗ (must end with / or contain /) - office/livingroom ✗ (first level doesn't match)
shell
Subscription: sensor+/# Matching topics: - sensor/001/ ✓ - sensor/001/data ✓ - sensor/001/data/temperature ✓ - sensor/002/data/humidity/value ✓ Non-matching topics: - sensor ✗ (too few levels) - office/001/data ✗ (first level doesn't match)

Combined Usage Examples

shell
Subscription: home/+/sensors/# Matching topics: - home/livingroom/sensors/ ✓ - home/livingroom/sensors/temperature ✓ - home/livingroom/sensors/temperature/value ✓ - home/bedroom/sensors/humidity ✓ Non-matching topics: - home/sensors/ ✗ (missing middle level) - home/livingroom/sensors ✗ (# must be at the end)

Wildcard Rules

Single-level Wildcard (+) Rules

  1. Matches Single Level: Can only match one non-empty level
  2. Can Be Used Multiple Times: Can appear multiple times in the topic filter
  3. Can Appear Anywhere: Can be used at any level of the topic
  4. Cannot Cross Levels: Cannot match multiple levels

Multi-level Wildcard (#) Rules

  1. Matches Multiple Levels: Can match zero or more levels
  2. Must Be at End: Must be the last character in the topic filter
  3. Can Only Be Used Once: Can only be used once per topic filter
  4. Must Follow /: If the topic has multiple levels, # must be preceded by /

Wildcard Use Cases

1. Device Category Monitoring

shell
Scenario: Monitor all temperature sensors Subscription: sensors/+/temperature Effect: Receive temperature data from all devices

2. Area Monitoring

shell
Scenario: Monitor all data in a specific area Subscription: building/floor1/# Effect: Receive data from all devices on the first floor

3. Device Status Monitoring

shell
Scenario: Monitor online status of all devices Subscription: device/+/status Effect: Receive status updates from all devices

4. Data Type Subscription

shell
Scenario: Subscribe to all alert messages Subscription: alert/# Effect: Receive all types of alerts

5. Hierarchical Subscription

shell
Scenario: Subscribe to all subtopics of a specific type Subscription: system/metrics/+/# Effect: Receive detailed data for all system metrics

Wildcard Limitations and Considerations

1. Publishing Limitations

  • Cannot Publish to Wildcard Topics: Wildcards can only be used for subscriptions, not publishing
  • Topics Must Be Explicit: Must specify the complete topic path when publishing

2. Subscription Limitations

  • Wildcards Cannot Be Used Within Topic Levels: Such as home/room+/temperature is invalid
  • # Must Be at End: home/#/temperature is invalid
  • + Cannot Match Empty: home/+/temperature cannot match home//temperature

3. Performance Considerations

  • Wildcard Subscriptions Increase Broker Burden: Broker needs to perform topic matching
  • Avoid Excessive Wildcard Use: Too many wildcard subscriptions may affect performance
  • Design Topic Structure Properly: Good topic design can reduce wildcard usage

4. Security Considerations

  • ACL Permission Control: Wildcard subscriptions require appropriate permissions
  • Avoid Over-authorization: Wildcard subscriptions may expose too much data
  • Principle of Least Privilege: Only grant necessary wildcard permissions

Code Examples

Python (paho-mqtt)

python
import paho.mqtt.client as mqtt def on_connect(client, userdata, flags, rc): print(f"Connected with result code {rc}") # Single-level wildcard subscription client.subscribe("sensor/+/temperature") # Multi-level wildcard subscription client.subscribe("home/bedroom/#") # Combined wildcard subscription client.subscribe("system/+/metrics/#") def on_message(client, userdata, msg): print(f"Received: {msg.topic} - {msg.payload.decode()}") client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("broker.example.com", 1883, 60) client.loop_forever()

JavaScript (MQTT.js)

javascript
const mqtt = require('mqtt'); const client = mqtt.connect('mqtt://broker.example.com'); client.on('connect', () => { console.log('Connected'); // Single-level wildcard subscription client.subscribe('sensor/+/temperature'); // Multi-level wildcard subscription client.subscribe('home/bedroom/#'); // Combined wildcard subscription client.subscribe('system/+/metrics/#'); }); client.on('message', (topic, message) => { console.log(`Received: ${topic} - ${message.toString()}`); });

Best Practices

1. Topic Design

  • Clear Hierarchy: Topic hierarchy should be clear and meaningful
  • Avoid Too Deep: Topic levels should not be too deep (recommended not to exceed 5 levels)
  • Use Separators: Consistently use / as separator
  • Naming Conventions: Use consistent naming conventions

2. Wildcard Usage

  • Use as Needed: Only use wildcards when necessary
  • Avoid Overly Broad Wildcards: Avoid using overly broad wildcards (like #)
  • Combine Wisely: Reasonably combine single-level and multi-level wildcards
  • Performance Optimization: Reduce wildcard usage in high-performance scenarios

3. Subscription Management

  • Unsubscribe Promptly: Unsubscribe from subscriptions that are no longer needed
  • Avoid Duplicate Subscriptions: Avoid subscribing to the same topic multiple times
  • Monitor Subscription Count: Monitor subscription count, avoid too many subscriptions

4. Security Management

  • Permission Control: Set appropriate permissions for wildcard subscriptions
  • Minimum Privilege: Only grant the necessary minimum permissions
  • Regular Review: Regularly review wildcard subscription permissions

Wildcard Performance Optimization

1. Broker Optimization

  • Choose Appropriate Broker: Choose a Broker that supports efficient wildcard matching
  • Configuration Optimization: Adjust Broker configuration based on actual needs
  • Cluster Deployment: Use cluster deployment for large-scale scenarios

2. Subscription Optimization

  • Exact Subscription Priority: Prioritize using exact topic subscriptions
  • Reduce Wildcard Levels: Reduce the number of levels matched by wildcards
  • Batch Subscriptions: Use batch subscriptions to reduce connection overhead

3. Topic Optimization

  • Topic Prefix: Use topic prefixes to reduce matching scope
  • Topic Grouping: Reasonably group topics to reduce wildcard usage
  • Avoid Wildcard Nesting: Avoid complex wildcard nesting

MQTT topic wildcards are an important mechanism for improving subscription flexibility. Proper use can simplify application logic and improve development efficiency. However, attention must be paid to performance and security issues, avoiding excessive use of wildcards.

标签:MQTT