插件窝 干货文章 如何测试linux搭建的mqtt

如何测试linux搭建的mqtt

测试 检查 MQTT mosquitto 304    来源:    2025-05-15

测试Linux搭建的MQTT服务的完整指南

基础测试方法

1. 使用命令行工具测试

mosquitto_pub/mosquitto_sub测试

# 订阅主题(在一个终端窗口)
mosquitto_sub -h localhost -t "test/topic" -v

# 发布消息(在另一个终端窗口)
mosquitto_pub -h localhost -t "test/topic" -m "Hello MQTT"

带认证测试(如果启用了认证)

mosquitto_pub -h localhost -t "test/topic" -m "auth test" -u username -P password

2. 检查MQTT服务状态

systemctl status mosquitto  # 对于使用systemd的系统
/etc/init.d/mosquitto status  # 对于使用init.d的系统

3. 检查端口监听

netstat -tulnp | grep 1883  # 默认非加密端口
netstat -tulnp | grep 8883  # 常用SSL/TLS端口

进阶测试方法

1. 使用MQTT.fx等GUI工具测试

  • 下载MQTT.fx(https://mqttfx.jensd.de/)
  • 配置连接参数(主机、端口、认证信息等)
  • 测试发布/订阅功能

2. 压力测试工具

使用mqtt-benchmark进行压力测试:

# 安装Node.js后
npm install -g mqtt-benchmark

# 运行基准测试
mqtt-benchmark --broker mqtt://localhost --count 1000 --size 200 --qos 2 --clients 10

3. TLS/SSL加密连接测试

# 使用mosquitto客户端测试SSL连接
mosquitto_sub -h localhost -p 8883 -t "test/topic" --cafile /path/to/ca.crt

自动化测试脚本

Python测试脚本示例(paho-mqtt库)

import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("test/topic")

def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("localhost", 1883, 60)
client.publish("test/topic", "Hello from Python")

client.loop_forever()

测试要点检查表

  1. 基本连接测试

    • 本地连接测试
    • 远程连接测试(如果适用)
    • 认证测试(用户名/密码)
  2. 功能测试

    • 发布/订阅消息
    • QoS级别测试(0,1,2)
    • 保留消息测试
    • 遗嘱消息测试
    • 通配符主题测试
  3. 性能测试

    • 连接数测试
    • 消息吞吐量测试
    • 延迟测试
  4. 安全测试

    • TLS/SSL加密连接
    • ACL权限测试
    • 异常输入测试
  5. 稳定性测试

    • 长时间运行测试
    • 断线重连测试
    • 高负载下的稳定性

常见问题排查

  1. 连接被拒绝

    • 检查服务是否运行
    • 检查防火墙设置
    • 检查配置文件中的监听设置
  2. 认证失败

    • 检查密码文件格式
    • 确认ACL权限设置
    • 检查用户名/密码是否正确
  3. 消息未收到

    • 检查主题名称是否匹配
    • 检查QoS级别设置
    • 检查客户端ID是否冲突
  4. 性能问题

    • 检查系统资源使用情况
    • 调整MQTT配置参数
    • 考虑集群部署

通过以上方法,您可以全面测试Linux环境下搭建的MQTT服务的功能、性能和稳定性。