Mosquitto介绍和简单使用
介绍
Eclipse Mosquitto是一个开源消息代理,实现了MQTT协议版本3.1和3.1.1。Mosquitto轻量,适用于低功耗单板计算机到完整服务器的所有设备。Mosquitto项目还提供了用于实现MQTT客户端的C库以及非常受欢迎的mosquitto_pub和mosquitto_sub命令行MQTT客户端。
安装
以Ubuntu16为例
添加到存储库列表
sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa
1
更新软件包
sudo apt-get update
1
安装
sudo apt-get install mosquitto
1
运行
sudo service mosquitto status
sudo service mosquitto start
sudo service mosquitto stop
1
2
3
安装命令行客户端
sudo apt-get install mosquitto-clients
1
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
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
1
服务开启后,输入如下命令,根据提示输入两遍密码
mosquitto_passwd /etc/mosquitto/pwfile 用户名
1
2.3 权限配置aclfile
打开文件
vim /etc/mosquitto/aclfile
1
编辑内容
# 李雷只能发布以test为前缀的主题,订阅以$SYS开头的主题即系统主题user lileitopic write test/#topic read $SYS/## 韩梅梅只能订阅以test为前缀的主题user hanmeimeitopic read test/#
1
3. 启动
-c:指定特定配置文件启动
-d:后台运行
mosquitto -c /etc/mosquitto/mosquitto.conf -d
1
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"
1
订阅系统主题
# 订阅客户端存活连接数mosquitto_sub -h localhost –t '$SYS/broker/clients/active' -u lilei -P 123456 -i "client2"
1
发布
mosquitto_pub -h localhost -t "test/abc" -u lilei -P 123456 -i "client3" -m "How are you?"
1
遇到问题
1.无法访问
[Mosquitto提示Starting in local only mode]:
2.端口未知
根据官方文档查看 端口为1883,因此使用前需要确认端口未被占用。