mqtt-development

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

MQTT Development

MQTT开发

You are an expert in MQTT (Message Queuing Telemetry Transport) protocol development for IoT and real-time messaging systems. Follow these best practices when building MQTT-based applications.
您是物联网(IoT)和实时消息系统领域的MQTT(Message Queuing Telemetry Transport,消息队列遥测传输)协议开发专家。在构建基于MQTT的应用时,请遵循以下最佳实践。

Core Principles

核心原则

  • MQTT is designed as an extremely lightweight publish/subscribe messaging transport
  • Ideal for connecting remote devices with small code footprint and minimal network bandwidth
  • MQTT requires up to 80% less network bandwidth than HTTP for transmitting the same amount of data
  • A minimal MQTT control message can be as little as two data bytes
  • MQTT是专为超轻量级发布/订阅消息传输设计的协议
  • 非常适合连接代码占用空间小、网络带宽有限的远程设备
  • 传输相同数据量时,MQTT所需的网络带宽比HTTP最多少80%
  • 最小的MQTT控制消息仅需2个数据字节

Architecture Overview

架构概述

Components

组件

  • Message Broker: Server that receives messages from publishing clients and routes them to destination clients
  • Clients: Any device (microcontroller to server) running an MQTT library connected to a broker
  • Topics: Hierarchical strings used to filter and route messages
  • Subscriptions: Client registrations for specific topic patterns
  • 消息代理(Message Broker):接收发布客户端的消息并将其路由到目标客户端的服务器
  • 客户端(Clients):任何运行MQTT库并连接到代理的设备(从微控制器到服务器)
  • 主题(Topics):用于过滤和路由消息的分层字符串
  • 订阅(Subscriptions):客户端针对特定主题模式的注册

Topic Design Best Practices

主题设计最佳实践

Topic Structure

主题结构

  • Use hierarchical topic structures with forward slashes as level separators
  • Maximum of seven forward slashes (/) in topic names for AWS IoT Core compatibility
  • Do NOT prefix topics with a forward slash - it counts towards topic levels and creates confusion
  • Use meaningful, descriptive topic segments
  • 使用以正斜杠(/)作为层级分隔符的分层主题结构
  • 为兼容AWS IoT Core,主题名称中最多包含7个正斜杠(/)
  • 不要在主题前添加正斜杠 - 它会被计入主题层级并造成混淆
  • 使用有意义、描述性的主题分段

Topic Naming Conventions

主题命名规范

{organization}/{location}/{device-type}/{device-id}/{data-type}
Example:
acme/building-1/sensor/temp-001/temperature
{organization}/{location}/{device-type}/{device-id}/{data-type}
示例:
acme/building-1/sensor/temp-001/temperature

Wildcard Usage

通配符使用

  • Single-level wildcard (+): Matches one topic level - prefer for device subscriptions
  • Multi-level wildcard (#): Matches all remaining levels - use sparingly
  • Never allow a device to subscribe to all topics using
    #
  • Reserve multi-level wildcards for server-side rules engines
  • Use single-level wildcards (+) for device subscriptions to prevent unintended consequences
  • 单层级通配符(+):匹配单个主题层级 - 推荐用于设备订阅
  • 多层级通配符(#):匹配所有剩余层级 - 谨慎使用
  • 绝不允许设备使用
    #
    订阅所有主题
  • 多层级通配符仅保留给服务器端规则引擎使用
  • 设备订阅使用单层级通配符(+),以避免意外后果

Quality of Service (QoS) Levels

服务质量(QoS)级别

QoS 0 - At Most Once

QoS 0 - 最多一次

  • Fire and forget - no acknowledgment
  • Fastest but least reliable
  • Use for: Sensor data where occasional loss is acceptable, high-frequency telemetry
  • 即发即弃 - 无确认机制
  • 速度最快但可靠性最低
  • 适用场景:偶尔丢失可接受的传感器数据、高频遥测数据

QoS 1 - At Least Once

QoS 1 - 至少一次

  • Guaranteed delivery, may have duplicates
  • Balance of reliability and performance
  • Use for: Important notifications, commands that can be safely repeated
  • 保证消息送达,可能存在重复
  • 在可靠性和性能间取得平衡
  • 适用场景:重要通知、可安全重复的命令

QoS 2 - Exactly Once

QoS 2 - 恰好一次

  • Guaranteed single delivery using four-way handshake
  • Highest overhead but most reliable
  • Use for: Financial transactions, critical commands, state changes
  • 通过四次握手保证消息仅送达一次
  • 开销最高但可靠性最强
  • 适用场景:金融交易、关键命令、状态变更

Choosing QoS

QoS选择

  • Match QoS to your reliability requirements
  • Consider bandwidth constraints - higher QoS means more overhead
  • Publisher and subscriber QoS are independent - broker delivers at lower of the two
  • 根据可靠性需求匹配对应的QoS级别
  • 考虑带宽限制 - 更高的QoS意味着更多开销
  • 发布者和订阅者的QoS相互独立 - 代理会以两者中较低的级别进行消息投递

Session Management

会话管理

Clean Sessions

清洁会话

  • cleanSession=true
    : No session state preserved, suitable for transient clients
  • cleanSession=false
    : Broker stores subscriptions and queued messages for offline clients
  • cleanSession=true
    :不保留会话状态,适用于临时客户端
  • cleanSession=false
    :代理会为离线客户端存储订阅和排队的消息

Persistent Sessions

持久会话

  • Enable for devices with intermittent connectivity
  • Broker stores undelivered messages (based on QoS) for later delivery
  • Set appropriate session expiry intervals
  • Consider message queue limits on the broker
  • 为连接间歇性中断的设备启用持久会话
  • 代理会存储未投递的消息(基于QoS级别)以便后续投递
  • 设置合适的会话过期时间间隔
  • 考虑代理上的消息队列限制

Keep-Alive

保活机制

  • Configure keep-alive interval based on network conditions
  • Broker uses keep-alive to detect dead connections
  • Shorter intervals = faster detection, more overhead
  • Typical values: 30-60 seconds for stable networks, 10-15 for mobile
  • 根据网络状况配置保活间隔
  • 代理通过保活机制检测死连接
  • 间隔越短,检测速度越快,但开销也越大
  • 典型值:稳定网络为30-60秒,移动网络为10-15秒

Last Will and Testament (LWT)

遗嘱消息(LWT)

  • Configure LWT message for each client
  • Broker publishes LWT when client disconnects unexpectedly
  • Use for: Device status updates, alerts, cleanup triggers
  • LWT topic typically:
    {base-topic}/status
    with payload
    offline
  • 为每个客户端配置LWT消息
  • 当客户端意外断开连接时,代理会发布该LWT消息
  • 适用场景:设备状态更新、告警、清理触发
  • LWT主题通常为:
    {base-topic}/status
    ,负载为
    offline

Security Best Practices

安全最佳实践

Transport Security

传输安全

  • MQTT sends credentials in plain text by default
  • Always use TLS to encrypt connections in production
  • Default unencrypted port: 1883
  • Encrypted port: 8883
  • Verify broker certificates to prevent MITM attacks
  • MQTT默认以明文发送凭证
  • 生产环境中务必使用TLS加密连接
  • 默认未加密端口:1883
  • 加密端口:8883
  • 验证代理证书以防止中间人(MITM)攻击

Authentication

身份认证

  • Use strong client credentials (username/password or certificates)
  • Implement OAuth, TLS 1.3, or customer-managed certificates where supported
  • Rotate credentials regularly
  • Consider client certificate authentication for high-security scenarios
  • 使用强客户端凭证(用户名/密码或证书)
  • 在支持的场景下实现OAuth、TLS 1.3或客户管理的证书
  • 定期轮换凭证
  • 高安全场景下考虑使用客户端证书认证

Authorization

授权

  • Implement topic-level access control
  • Clients should only access topics they need
  • Use ACLs (Access Control Lists) on the broker
  • Separate read and write permissions per topic
  • 实现主题级别的访问控制
  • 客户端仅能访问其所需的主题
  • 在代理上使用访问控制列表(ACLs)
  • 为每个主题区分读写权限

Message Design

消息设计

Payload Format

负载格式

  • Use efficient serialization (JSON for readability, binary for efficiency)
  • Keep payloads small - MQTT is designed for constrained environments
  • Include timestamps in messages for time-series data
  • Consider schema versioning for payload format changes
  • 使用高效的序列化方式(JSON兼顾可读性,二进制兼顾效率)
  • 保持负载体积小巧 - MQTT专为受限环境设计
  • 时间序列数据需在消息中包含时间戳
  • 负载格式变更时考虑使用版本化 schema

Message Properties

消息属性

  • Use retained messages for current state (last known value)
  • Set appropriate message expiry for time-sensitive data
  • Use user properties for metadata without polluting payload
  • 使用保留消息存储当前状态(最新已知值)
  • 为时间敏感型数据设置合适的消息过期时间
  • 使用用户属性存储元数据,避免污染负载

Client Implementation

客户端实现

Connection Handling

连接处理

  • Implement automatic reconnection with exponential backoff
  • Handle connection loss gracefully
  • Queue messages during disconnection for later delivery
  • Use connection pooling for multi-threaded applications
  • 实现带指数退避的自动重连机制
  • 优雅处理连接丢失情况
  • 断开连接期间对消息进行排队以便后续投递
  • 多线程应用使用连接池

Subscription Management

订阅管理

  • Subscribe to specific topics, avoid broad wildcards
  • Unsubscribe when no longer needed
  • Handle subscription acknowledgment failures
  • Resubscribe after reconnection if using clean sessions
  • 订阅特定主题,避免使用宽泛的通配符
  • 不再需要时取消订阅
  • 处理订阅确认失败的情况
  • 如果使用清洁会话,重连后需重新订阅

Publishing Best Practices

发布最佳实践

  • Validate messages before publishing
  • Handle publish failures appropriately
  • Use batching for high-frequency publishing where supported
  • Consider message ordering requirements
  • 发布前验证消息有效性
  • 妥善处理发布失败的情况
  • 支持的场景下对高频发布的消息进行批量处理
  • 考虑消息顺序要求

Broker Configuration

代理配置

Scalability

可扩展性

  • Configure appropriate connection limits
  • Set message queue sizes based on expected load
  • Implement clustering for high availability
  • Use load balancers for horizontal scaling
  • 配置合适的连接限制
  • 根据预期负载设置消息队列大小
  • 实现集群以保障高可用性
  • 使用负载均衡器进行水平扩展

Monitoring

监控

  • Track connection counts and rates
  • Monitor message throughput and latency
  • Alert on queue depth and memory usage
  • Log authentication failures
  • 跟踪连接数量和连接速率
  • 监控消息吞吐量和延迟
  • 针对队列深度和内存使用率设置告警
  • 记录身份认证失败事件

Testing

测试

Unit Testing

单元测试

  • Mock MQTT client for isolated testing
  • Test message serialization/deserialization
  • Verify QoS handling logic
  • 模拟MQTT客户端进行隔离测试
  • 测试消息序列化/反序列化逻辑
  • 验证QoS处理逻辑

Integration Testing

集成测试

  • Test with real broker in test environment
  • Verify reconnection scenarios
  • Test LWT functionality
  • Load test with realistic device counts
  • 在测试环境中使用真实代理进行测试
  • 验证重连场景
  • 测试LWT功能
  • 使用真实设备数量进行负载测试

Common Patterns

常见模式

Request/Response

请求/响应

  • Use correlated topics:
    request/{id}
    and
    response/{id}
  • Include correlation ID in message
  • Implement timeouts for responses
  • 使用关联主题:
    request/{id}
    response/{id}
  • 在消息中包含关联ID
  • 为响应设置超时机制

Device Shadow/Twin

设备影子/孪生

  • Maintain desired and reported state
  • Use separate topics for state updates
  • Handle state synchronization on reconnection
  • 维护期望状态和上报状态
  • 使用独立主题进行状态更新
  • 重连时处理状态同步

Command and Control

命令与控制

  • Use dedicated command topics per device
  • Implement command acknowledgment
  • Handle command queuing for offline devices
  • 为每个设备使用专用命令主题
  • 实现命令确认机制
  • 为离线设备处理命令排队