作为一个硬件爱好者,在服务器上安装 MQTT 服务器,可以实现物联网设备的远程连接交互.
Mosquitto 是一个开源的 MQTT 服务端程序,支持 MQTT 3.1 和 3.1.1 协议和最新的 5.0.0, 并支持 TLS/SSL 安全连接.
此次安装新的服务器,也把 Mosquitto 最新版给安装上,安装过程如下:
# 安装必要的软件包
首先要安装编译所需的一些软件包,有一些是在 centos8.6 中默认就有的,有的则需要另外安装.
dnf install cmake cjson-devel cjson libwebsockets libwebsockets-devel --skip-broken | |
## 加 --skip-broken 是因为安装 libwebsockets-devel 可能会出现依赖问题,所以直接跳过. |
# 下载源码包
下载地址:Mosquitto-Download
这里选择最上面的 mosquitto-2.0.18.tar.gz
# 解压缩并编译
下载下来之后解压缩,然后进入解压缩后的目录,执行如下命令:
tar -zxvf mosquitto-2.0.18.tar.gz | |
cd mosquitto-2.0.18 | |
cmake . | |
make WITH_WEBSOCKETS=yes WITH_CJSON=yes | |
make install |
等待安装完成即可.
# 配置 Mosquitto
刚编译安装完成,还需要配置 mosquitto, 配置文件位于 /etc/mosquitto/mosquitto.conf
, 但是此时该文件还没有
源码目录中有个 mosquitto.conf
, 复制到 /etc/mosquitto
目录下即可.
mkdir /etc/mosquitto | |
cp ./mosquitto.conf /etc/mosquitto/ |
创建一个名为 mosquitto 的用户,作为 mosquitto 的运行用户
useradd -m -s /usr/sbin/nologin mosquitto
然后修改 mosquitto.conf
文件,主要有以下几项需要改动
# 允许匿名用户连接 设为 false | |
allow_anonymous false | |
# 使用 mosquitto 用户运行该程序 | |
user mosquitto | |
# 监听到 1883 端口 | |
listener 1883 | |
# 设置日志文件地址 | |
log_dest file /home/mosquitto/mosquitto.log | |
# 设置日志等级 | |
log_type warning | |
# 指定用户密码文件 | |
password_file /etc/mosquitto/pwfile | |
# 指定用户 acl 文件 | |
acl_file /etc/mosquitto/aclfile |
此时还没有 pwfile, 就创建一个
touch /etc/mosquitto/pwfile
然后创建第一个用户 admin , 并设置密码
mosquitto_passwd /etc/mosquitto/pwfile admin
配置 acl 权限
vim /etc/mosquitto/aclfile | |
# 格式如下 暂且不设置 | |
# 李雷只能发布以 test 为前缀的主题,订阅以 $SYS 开头的主题即系统主题 | |
user lilei | |
topic write test/# | |
topic read $SYS/# | |
# 韩梅梅只能订阅以 test 为前缀的主题 | |
user hanmeimei | |
topic read test/# |
这里要把 aclfile 和 pwfile 文件权限设置为 mosquitto 用户,并且权限是 0777
chown mosquitto /etc/mosquitto/pwfile | |
chgrp mosquitto /etc/mosquitto/pwfile | |
chown mosquitto /etc/mosquitto/aclfile | |
chgrp mosquitto /etc/mosquitto/aclfile | |
chmod 0700 /etc/mosquitto/pwfile | |
chmod 0700 /etc/mosquitto/aclfile |
# 启动 Mosquitto
一条命令启动 mosquitto 服务
mosquitto -c /etc/mosquitto/mosquitto.conf -d
查看一下 mosquitto 服务是否启动
# netstat -anp|grep 1883 | |
tcp 0 0 127.0.0.1:1883 0.0.0.0:* LISTEN 96109/mosquitto | |
tcp6 0 0 ::1:1883 :::* LISTEN 96109/mosquitto |
服务已经启动起来了
# 测试
下载一个客户端,这里使用 MQTTX 客户端,下载地址:MQTTX-Download
使用我们设置的 admin 账户和密码连接,随便发送一个 topic
# 使用 systemd 管理 Mosquitto 服务
# vim /etc/systemd/system/mosquitto.service | |
[Unit] | |
Description=Mosquitto MQTT Broker | |
Documentation=https://mosquitto.org/ | |
After=network.target | |
[Service] | |
Type=simple | |
ExecStart=/usr/local/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf | |
Restart=always | |
[Install] | |
WantedBy=multi-user.target |
更新 systemd 配置文件systemctl daemon-reload
启动服务systemctl start mosquitto.service
设置为开机启动systemctl enable mosquitto.service
# 结束
至此, mosquitto
服务器已经安装完成!