#1、 安装
sudo apt install mosquitto mosquitto-clients
#2、 查看状态
sudo systemctl status mosquitto
#3、 查看已安装的配置文件信息
cat /etc/mosquitto/mosquitto.conf
# 内容如下
# Place your local configuration in /etc/mosquitto/conf.d/
#
# A full description of the configuration file is at
# /usr/share/doc/mosquitto/examples/mosquitto.conf.example
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
#4、 新增自己的配置只需要在 /etc/mosquitto/conf.d 目录下添加配置文件即可
vim /etc/mosquitto/conf.d/my_mqtt.conf
# 填写以下内容
# 监听 TCP 端口
listener 1883
protocol mqtt
# 监听 WebSocket 端口
listener 8083
protocol websockets
# 设置最大连接数
max_connections 1000
# 允许匿名连接(测试时可开启,生产环境建议关闭)
allow_anonymous false
# 密码文件位置
password_file /etc/mosquitto/passwd
# ACL 文件位置
acl_file /etc/mosquitto/acl
# 配置acl控制文件
vim /etc/mosquitto/acl
# 输入以下内容
# 用户 your_username 对所有主题有读写权限
user your_username
topic readwrite #
# 用户 another_user 只能订阅特定主题
#user another_user
#topic read sensor/#
#topic write control/#
#5、 首次创建密码文件(使用 -c 参数) your_username 改为自己需要创建的用户名称,然后输入回车输入密码
sudo mosquitto_passwd -c /etc/mosquitto/passwd your_username
# 后续添加用户(不使用 -c 参数)
sudo mosquitto_passwd /etc/mosquitto/passwd another_user
#6、 调整系统并发连接数
vim /etc/security/limits.conf
# 增加以下内容 根据 设定的 max_connections 设置调整
* soft nofile 1000
* hard nofile 1000
mosquitto soft nofile 1000
mosquitto hard nofile 1000
#7、设置文件权限
sudo chown mosquitto:mosquitto /etc/mosquitto/passwd /etc/mosquitto/acl
sudo chmod 600 /etc/mosquitto/passwd /etc/mosquitto/acl
#8、启动 并设置为开机自启动
systemctl start mosquitto
systemctl enable mosquitto
# 证书配置 ssl.conf
vim /etc/mosquitto/conf.d/ssl.conf
# 输入以下内容
listener 8883 # MQTTS 端口
protocol mqtt
certfile /etc/letsencrypt/live/yourdomain.com/cert.pem
keyfile /etc/letsencrypt/live/yourdomain.com/privkey.pem
cafile /etc/letsencrypt/live/yourdomain.com/chain.pem
# 强制客户端使用 TLS
require_certificate true
# Nginx代理 端口记得配置正确了 切记TCP代理不允许代理server已经代理的端口,比如80,443,http请求会经过tcp直接拦截 端口都是唯一的即可
# tcp
stream {
upstream your_mqtt_server {
server 192.168.0.100:1883;
}
server {
listen 9999;
proxy_pass your_mqtt_server;
}
}
# websocket
server {
listen 9091;
server_name localhost 你的IP;
location /mqtt {
# 启用 WebSocket 代理
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header Host $host;
# 设置代理目标地址
proxy_pass http://192.168.0.100:8083/mqtt;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}