跳转至

实验:MQTT 可靠性

预计:90 分钟|验证:Topic、QoS、Retain、Will

准备 Broker

docker run --rm --name kb-mqtt -p 1883:1883 \
  eclipse-mosquitto:2 mosquitto -c /mosquitto-no-auth.conf

以下命令可用本机安装的 Mosquitto 客户端,或进入容器执行。

实验一:发布订阅

订阅:

mosquitto_sub -h 127.0.0.1 -t 'tenant/1/device/+/telemetry' -v

发布:

mosquitto_pub -h 127.0.0.1 \
  -t 'tenant/1/device/1001/telemetry' \
  -m '{"temperature": 26.5}'

观察 + 只匹配一个 Topic 层级。

实验二:Retained Message

mosquitto_pub -h 127.0.0.1 \
  -t 'tenant/1/device/1001/config' \
  -m '{"interval":30}' -r

发布结束后再启动新订阅者:

mosquitto_sub -h 127.0.0.1 \
  -t 'tenant/1/device/1001/config' -C 1 -v

新订阅者会立即收到最后的保留消息。它不是历史消息列表。

实验三:Will

启动带遗嘱的长连接客户端:

mosquitto_sub -h 127.0.0.1 \
  -i device-1001 \
  -t 'tenant/1/device/1001/command' \
  --will-topic 'tenant/1/device/1001/status' \
  --will-payload 'offline'

另一个终端订阅状态 Topic,然后强制结束第一个客户端。观察 Broker 发布遗嘱。

思考:

  • 正常退出是否相同?
  • 网络抖动导致遗嘱后设备立刻重连怎么办?
  • 为什么最终业务状态仍需版本或 last_seen 校验?

实验四:QoS 1 思维实验

QoS 1 保证至少一次。即使本机实验未稳定复现重复,也要在业务消费者中主动发送两次相同 message_id,验证告警或工单不会重复创建。

实验报告

  • 能解释 Topic 通配符
  • 能说明 Retain 只保存最后一条
  • 能说明 Will 是信号,不是最终事实
  • 能解释 QoS 1 与业务幂等