MQTT服务器搭建
尝试过搭建mosquitto,但ws和wss无法访问,导致web端无法通过websocket协议连接mqtt;也尝试过node(mosca)+nginx搭建,也是出现wss无法连接问题。最后尝试了搭建EMQX成功实现mqtt:// 、ws://、wss:// 连接。
一、服务器准备
阿里云或腾讯云自行购买;
二、安装EMQ
官网地址:https://www.emqx.com/zh/downloads?product=broker
个人使用安装开源版即可,然后选择服务器系统,或者使用docker部署(我个人安装的是Ubuntu版本的)
wget安装
-
下载zip包(此链接是下载4.4.3版本的)
wget https://www.emqx.com/zh/downloads/broker/4.3-rc.5/emqx-ubuntu20.04-4.3-rc.5-amd64.zip提示:如果想下载新版本的可以到
https://www.emqx.com/zh/downloads/broker查看最新版本后下载相应版本; -
安装
unzip emqx-ubuntu20.04-4.3-rc.5-amd64.zip -
运行
./bin/emqx start
命令行安装
-
安装所需要的依赖包
sudo apt update && sudo apt install -y \ apt-transport-https \ ca-certificates \ curl \ gnupg-agent \ software-properties-common -
添加 EMQ X 的官方 GPG 密钥
curl -fsSL https://repos.emqx.io/gpg.pub | sudo apt-key add -验证密钥
sudo apt-key fingerprint 3E640D53 pub rsa2048 2019-04-10 [SC] FC84 1BA6 3775 5CA8 487B 1E3C C0B4 0946 3E64 0D53 uid [ unknown] emqx team <support@emqx.io> -
使用以下命令设置 stable 存储库。 如果要添加 unstable 存储库,请在以下命令中的单词 stable 之后添加单词 unstable。
sudo add-apt-repository \ "deb [arch=amd64] https://repos.emqx.io/emqx-ce/deb/ubuntu/ \ ./$(lsb_release -cs) \ stable" -
更新 apt 包索引
sudo apt update -
安装最新版本的 EMQ X Broker
sudo apt install emqx
三、启动
后台启动 EMQ X
emqx start
systemctl 启动
sudo systemctl start emqx
service 启动
sudo service emqx start
四、基本命令
启动
sudo service emqx start
重启
sudo service emqx restart
停止
sudo service emqx stop
查看状态
sudo service emqx status
五、端口详情
| 端口 | 说明 |
|---|---|
| 1883 | MQTT/TCP 协议端口 |
| 11883 | MQTT/TCP 协议内部端口,仅用于本机客户端连接 |
| 8883 | MQTT/SSL 协议端口 |
| 8083 | MQTT/WS 协议端口 |
| 8084 | MQTT/WSS 协议端口 |
六、开启连接校验
Mnesia 认证
Mnesia 认证使用 EMQ X 内置 Mnesia 数据库存储客户端 Client ID/Username 与密码,支持通过 HTTP API 管理认证数据。
Mnesia 认证不依赖外部数据源,使用上足够简单轻量
插件:emqx_auth_mnesia
注意:启动该插件才能进行用户名和密码连接
启动匿名认证
#etc/emqx.conf
##Value: true | false
allow_anonymous = false
加盐规则与哈希方法配置
#etc/plugins/emqx_auth_mysql.conf
##不加盐,仅做哈希处理
auth.mysql.password_hash = sha256
##salt 前缀:使用 sha256 加密 salt + 密码 拼接的字符串
auth.mysql.password_hash = salt,sha256
##salt 后缀:使用 sha256 加密 密码 + salt 拼接的字符串
auth.mysql.password_hash = sha256,salt
设置可登录用户名密码
#etc/plugins/emqx_auth_mysql.conf
##Examples:
auth.user.1.username = xxx ##用户名
auth.user.1.password = xxx ##密码
##auth.user.2.username = feng@emqtt.io
##auth.user.2.password = public
##auth.user.3.username = name~!@#$%^&*()_+
##auth.user.3.password = pwsswd~!@#$%^&*()_+
root@iZwz9207qjiw20qn3x44jdZ:/etc/emqx/plugins#
最后
执行sudo service emqx restart 重启服务即可生效
访问http://域名或ip:18083/即可访问Dashboard控制台,默认用户名admin,密码public
彩蛋
nginx代理实现wss连接
不配置:只能通过mqtt://xxxx:1883连接,导致web端不能连接;
配置:web端可通过wss://xxxx/mqtt连接
upstream mqtt{
server 127.0.0.1:8083;
keepalive 64;
}
location /mqtt {
proxy_redirect off;
proxy_pass http://mqtt;
proxy_set_header Host $host;
proxy_set_header X-Real_IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr:$remote_port;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
}