MQTT's publish/subscribe pattern is a messaging architecture that decouples message producers and consumers, enabling flexible one-to-many communication.
Core Concepts
1. Topic
- Definition: A topic is the routing address for messages, using a hierarchical structure
- Format: String separated by slashes (/), such as
home/livingroom/temperature - Features:
- Clear hierarchy for easy organization and management
- Supports wildcard subscriptions
- Case-sensitive
- Length limit: maximum 65535 bytes
2. Publisher
- Role: Message producer
- Function: Sends messages to specific topics
- Features:
- Doesn't need to know about subscribers
- Can publish to multiple topics simultaneously
- Returns immediately after publishing, doesn't wait for subscriber response
3. Subscriber
- Role: Message consumer
- Function: Subscribes to topics of interest and receives relevant messages
- Features:
- Can subscribe to multiple topics
- Can use wildcards to subscribe to a category of topics
- Only receives messages published after subscription
4. Broker
- Role: Message relay and router
- Functions:
- Receives messages from publishers
- Distributes messages to subscribers based on subscription relationships
- Manages client connections and sessions
- Handles QoS guarantees for messages
Workflow
- Connection Establishment: Clients (publishers/subscribers) connect to the Broker
- Topic Subscription: Subscribers send subscription requests to the Broker
- Message Publishing: Publishers send messages to specific topics
- Message Routing: Broker receives messages and finds clients subscribed to that topic
- Message Distribution: Broker forwards messages to all subscribers
- Message Reception: Subscribers receive and process messages
Wildcard Subscriptions
Single-level Wildcard (+)
- Matches a single level
- Example:
home/+/temperaturematcheshome/livingroom/temperature, but nothome/livingroom/kitchen/temperature
Multi-level Wildcard (#)
- Matches multiple levels, must be at the end of the topic
- Example:
home/#matches all topics underhome/
Advantages
- Decoupling: Publishers and subscribers are completely decoupled, independent of each other
- Flexibility: Supports one-to-many, many-to-one, and many-to-many communication patterns
- Scalability: Easy to add new publishers and subscribers
- Asynchrony: Publishers don't need to wait for subscriber responses
- Efficiency: Broker handles message routing, reducing network overhead
Comparison with Point-to-Point Pattern
| Feature | Publish/Subscribe | Point-to-Point |
|---|---|---|
| Coupling | Low | High |
| Message Receivers | Multiple | One |
| Message Persistence | Optional | Usually required |
| Complexity | Medium | Simple |
| Use Cases | Broadcasting, Notifications | Direct Communication |
MQTT's publish/subscribe pattern makes it an ideal choice for IoT, real-time communication, and message push scenarios.