Mosquitto 搭建及配置

简书_Mosquitto 搭建及配置

Eclipse Mosquitto是一个开源消息代理,实现了MQTT协议版本3.1和3.1.1。Mosquitto轻量,适用于低功耗单板计算机到完整服务器的所有设备。Mosquitto项目还提供了用于实现MQTT客户端的C库以及非常受欢迎的mosquitto_pub和mosquitto_sub命令行MQTT客户端。

其他服务器代理实现:https://github.com/mqtt/mqtt.github.io/wiki/servers
各操作系统安装指引:https://mosquitto.org/download/

1. 下载安装

以Ubuntu16为例

  • 添加到存储库列表
sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa
  • 更新软件包
sudo apt-get update
  • 安装
sudo apt-get install mosquitto
  • 安装命令行客户端
sudo apt-get install mosquitto-clients

2. 配置

2.1 主配置文件mosquitto.conf
pid_file /var/run/mosquitto.pid

# 消息持久存储
persistence true
persistence_location /var/lib/mosquitto/

# 日志文件
log_dest file /var/log/mosquitto/mosquitto.log

# 其他配置
include_dir /etc/mosquitto/conf.d

# 禁止匿名访问
allow_anonymous false
# 认证配置
password_file /etc/mosquitto/pwfile
# 权限配置
acl_file /etc/mosquitto/aclfile

2.2 认证配置pwfile
  • 没有则创建文件
touch /etc/mosquitto/pwfile
  • 服务开启后,输入如下命令,根据提示输入两遍密码
mosquitto_passwd /etc/mosquitto/pwfile 用户名
2.3 权限配置aclfile
  • 打开文件
vim /etc/mosquitto/aclfile
  • 编辑内容
# 李雷只能发布以test为前缀的主题,订阅以$SYS开头的主题即系统主题
user lilei
topic write test/#
topic read $SYS/#

韩梅梅只能订阅以test为前缀的主题

user hanmeimei
topic read test/#

3. 启动

-c:指定特定配置文件启动
-d:后台运行

mosquitto -c /etc/mosquitto/mosquitto.conf -d

4. 测试

发布使用mosquitto_pub命令,订阅使用mosquitto_sub命令。常用参数介绍:

参数 描述
-h 服务器主机,默认localhost
-t 指定主题
-u 用户名
-P 密码
-i 客户端id,唯一
-m 发布的消息内容

订阅

mosquitto_sub -h localhost -t "test/#" -u hanmeimei -P 123456 -i "client1"

订阅系统主题

# 订阅客户端存活连接数
mosquitto_sub -h localhost –t '$SYS/broker/clients/active' -u lilei -P 123456 -i "client2"

发布

mosquitto_pub -h localhost -t "test/abc" -u lilei -P 123456 -i "client3" -m "How are you?"

mosquitto_pub 命令参数说明

  1. -d 打印debug信息

  2. -f 将指定文件的内容作为发送消息的内容

  3. -h 指定要连接的域名 默认为localhost

  4. -i 指定要给哪个clientId的用户发送消息

  5. -I 指定给哪个clientId前缀的用户发送消息

  6. -m 消息内容

  7. -n 发送一个空(null)消息

  8. -p 连接端口号

  9. -q 指定QoS的值(0,1,2)

  10. -t 指定topic

  11. -u 指定broker访问用户

  12. -P 指定broker访问密码

  13. -V 指定MQTT协议版本

  14. –will-payload 指定一个消息,该消息当客户端与broker意外断开连接时发出。该参数需要与–will-topic一起使用

  15. –will-qos Will的QoS值。该参数需要与–will-topic一起使用

  16. –will-retain 指定Will消息被当做一个retain消息(即消息被广播后,该消息被保留起来)。该参数需要与–will-topic一起使用

  17. –will-topic 用户发送Will消息的topic

mosquitto_sub 命令参数说明

  1. -c 设定‘clean session’为无效状态,这样一直保持订阅状态,即便是已经失去连接,如果再次连接仍旧能够接收的断开期间发送的消息。

  2. -d 打印debug信息

  3. -h 指定要连接的域名 默认为localhost

  4. -i 指定clientId

  5. -I 指定clientId前缀

  6. -k keepalive 每隔一段时间,发PING消息通知broker,仍处于连接状态。 默认为60秒。

  7. -q 指定希望接收到QoS为什么的消息 默认QoS为0

  8. -R 不显示陈旧的消息

  9. -t 订阅topic

  10. -v 打印消息

  11. –will-payload 指定一个消息,该消息当客户端与broker意外断开连接时发出。该参数需要与–will-topic一起使用

  12. –will-qos Will的QoS值。该参数需要与–will-topic一起使用

  13. –will-retain 指定Will消息被当做一个retain消息(即消息被广播后,该消息被保留起来)。该参数需要与–will-topic一起使用

  14. –will-topic 用户发送Will消息的topic

链接
发布了17 篇原创文章 · 获赞 0 · 访问量 220

猜你喜欢

转载自blog.csdn.net/neheqi/article/details/105343330