MQTT服务(EMQX)安装

安装及测试EMQ X

  EMQ X R3.0 (Erlang/Enterprise/Elastic MQTT Broker) 是基于 Erlang/OTP 语言平台开发,支持大规模连接和分布式集群,发布订阅模式的开源 MQTT 消息服务器。

  MQTT是一个由IBM主导开发的物联网传输协议,它被设计用于轻量级的发布/订阅式消息传输,旨在为低带宽和不稳定的网络环境中的物联网设备提供可靠的网络服务。它的核心设计思想是开源、可靠、轻巧、简单,具有以下主要的几项特性:
1.非常小的通信开销(最小的消息大小为 2 字节);
2.支持各种流行编程语言(包括C,Java,Ruby,Python 等等)且易于使用的客户端;
3.支持发布 / 预定模型,简化应用程序的开发;
4.提供三种不同消息传递等级,让消息能按需到达目的地,适应在不稳定工作的网络传输需求。

官方网址:https://www.emqx.io/

1. 二进制rpm包安装

1.1. Ubuntu

    download: https://www.emqx.io/downloads/broker?osType=Linux
    #example bin url: https://www.emqx.io/downloads/broker/v4.0.5/emqx-ubuntu16.04-v4.0.5.zip
    unzip emqx-ubuntu16.04-v4.0.5.zip && cd emqx

    # start emqx
    ./bin/emqx start

    # Check the running status
    ./bin/emqx_ctl status

    # stop emqx
    ./bin/emqx stop

    MQTT can connect it though port 1883
    web console: http://127.0.0.1:18083,default username: admin,password:public

1.2. CentOS

  • Centos7操作系统
#yum install https://www.emqx.io/downloads/broker/v4.0.5/emqx-centos7-v4.0.5.x86_64.rpm
yum install -y https://www.emqx.com/zh/downloads/broker/v4.4.19/emqx-4.4.19-otp24.3.4.2-1-el7-amd64.rpm
# start emqx
systemctl start emqx
# start emqx when reboot/power-on
systemctl enable emqx
  • 官方连接直接安装,Centos8操作系统
dnf update
dnf search emqx
dnf install emqx  #发现有emqx对应的包

# 下载 openssl11
sudo dnf install -y https://download-ib01.fedoraproject.org/pub/epel/8/Everything/x86_64/Packages/o/openssl11-1.1.1k-3.el8.x86_64.rpm
sudo dnf install -y https://www.emqx.com/en/downloads/broker/v4.4.19/emqx-4.4.19-otp24.3.4.2-1-el8-amd64.rpm
systemctl start emqx
# start emqx when reboot/power-on
systemctl enable emqx

1.3. 源码编译安装

install Erlang
install rebar3: A sophisticated build-tool for Erlang projects that follows OTP principles

#Get the source code

$ git clone -b v3.2.0 https://github.com/emqx/emqx-rel.git
#Set environment variables

$ export EMQX_DEPS_DEFAULT_VSN=v3.2.0
#Compile

$ cd emqx-rel && make
#Start EMQ X

$ cd _build/emqx/rel/emqx
$ ./bin/emqx start
emqx v3.2.0 is started successfully!

$ ./bin/emqx_ctl status
Node 'emqx@127.0.0.1' is started
emqx 3.2.0 is running

1.4. docker 安装

  • 如果你选择使用 Docker 安装 EMQ X,需要先安装 Docker。以 Ubuntu 系统为例:
# 更新系统包列表
sudo apt update
# 安装必要的依赖
sudo apt install apt-transport-https ca-certificates curl software-properties-common
# 添加 Docker 的官方 GPG 密钥
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
# 添加 Docker 软件源
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
# 更新系统包列表
sudo apt update
# 安装 Docker
sudo apt install docker-ce docker-ce-cli containerd.io
# 启动 Docker 服务
sudo systemctl start docker
# 设置 Docker 开机自启
sudo systemctl enable docker
  • 安装emqx
# 拉取 EMQ X 镜像
docker pull emqx/emqx:5.0
# 运行 EMQ X 容器
docker run -d --name emqx -p 1883:1883 -p 8083:8083 -p 8084:8084 -p 8883:8883 -p 18083:18083 emqx/emqx:5.0

2. EMQX修改配置

2.1. 配置介绍

Emqx 的配置文件位于 /etc/emqx/目录下。你可以根据需要进行配置,例如开启认证功能。其中certs,lwm2m_xml, plugins都为文件夹;
以下是一个简单示例:

tree -L 1
.
├── certs
├── lwm2m_xml
├── plugins
├── acl.conf
├── emqx.conf
├── psk.txt
├── ssl_dist.conf
└── vm.args
File    Description
etc/emqx.conf   EMQ X 3.0 Configuration File
etc/acl.conf    The default ACL File
etc/plugins/*.conf  Config Files of Plugins

Configuration file processing flow during EMQ X start-up::

----------------------                                          3.0/schema/*.schema      -------------------
| etc/emqx.conf      |                   -----------------              \|/              | data/app.config |
|       +            | --> mergeconf --> | data/app.conf | -->  cuttlefish generate  --> |                 |
| etc/plugins/*.conf |                   -----------------                               | data/vm.args    |
----------------------                                                                   -------------------

EMQ X Node Connection Method:
    ##  Specify the Erlang Distributed Communication Protocol: inet_tcp | inet6_tcp | inet_tls
    node.proto_dist = inet_tcp

    Files for storing SSL/TLS options when Erlang distributed using TLS:
    node.ssl_dist_optfile = etc/ssl_dist.conf

MQTT/SSL Listener - 8883
    SSL listening port:
    listener.ssl.external = 8883
    Path of the file containing the user’s private key:
    listener.ssl.external.keyfile = etc/certs/key.pem

    Path of the file containing the user certificate:
    listener.ssl.external.certfile = etc/certs/cert.pem

    Path of the file containing the CA certificate:
    ## listener.ssl.external.cacertfile = etc/certs/cacert.pem

2.2. 监听地址和端口

默认情况下,Emqx 监听 1883 端口。你可以修改配置文件/etc/emqx/emqx.conf来监听其他地址和端口:

## Examples: 1883, 127.0.0.1:1883, ::1:1883
listener.tcp.external = 0.0.0.0:1883
## The acceptor pool for external MQTT/TCP listener.
listener.tcp.external.acceptors = 8
## Maximum number of concurrent MQTT/TCP connections.
##
listener.tcp.external.max_connections = 1024000
## Maximum external connections per second.
##
listener.tcp.external.max_conn_rate = 1000

2.3. wss 安全连接配置

2.3.1. 准备 SSL 证书和私钥

证书文件:将您的域名证书(如 xxx.cn.crt 或 .pem)和私钥(如 xxx.cn.key)放置于 EMQX 可访问的目录,例如 /etc/emqx/certs/。
证书链:如果证书包含中间证书,可以将服务器证书与中间证书合并(可选)。也可以直接查看所申请域名的证书链。

cat xxx.cn.crt intermediate.crt > combined.crt
  • 本人这里采用的亚信的证书,通过如下链接验证证书工具链 可以查看到整个证书链,放到combined.crt里;

2.3.2. 修改 EMQX 配置文件

打开配置文件 emqx.conf(通常位于 /etc/emqx/emqx.conf),添加或修改以下内容:

找到listener.wss.external.keyfile、listener.wss.external.certfile,把默认的修改为如下; server_private.key和 server_combined.crt 根据实际情况填写; 其他不动,核心是替换其中证书文件路径;

# 启用 WSS 监听器
## Examples: 8084, 127.0.0.1:8084, ::1:8084
listener.wss.external = 8084

## The path of WebSocket MQTT endpoint
listener.wss.external.mqtt_path = /mqtt

## Path to the file containing the user's private PEM-encoded key.
# 这个通常改为私钥,例如  /etc/emqx/certs/abcd.com.key
listener.wss.external.keyfile = /etc/emqx/certs/server_private.key

## Path to a file containing the user certificate.
## See: listener.ssl.$name.certfile
# 这个通常为公钥的全链路证书, 例如 /etc/emqx/certs/combined.crt
listener.wss.external.certfile = /etc/emqx/certs/server_combined.crt

2.3.3. 设置文件权限

确保 EMQX 用户有权限读取证书文件:因为emqx默认是emqx用户执行采用,所以这里改一下证书文件的所属用户;

chmod 600 /etc/emqx/certs/*
chown -R emqx:emqx /etc/emqx/certs/

2.3.4. 重启 EMQX 服务

应用配置更改:

systemctl restart emqx  # 或通过 emqx restart 重启

2.3.5. 验证 WSS 连接

使用 openssl 或在线工具测试:

openssl s_client -connect xxx.cn:8084 -showcerts

2.3.6. 安全认证相关简述

authetication is provided by a seriers of authentication plugins
supports authentication by username, password, ClientID or anonymous
anonymous is default
Multiple auth plug-ins can be started at the same time. The plug-in that starts first checks first.

Username Auth -> ClientID Auth -> Anonymous Auth

Modify etc/emqx.conf 

enable anonymous authentication:
    allow_anonymous = true

Access Control List:
    acl_nomatch = allow
    acl_file = etc/acl.conf

    etc/acl.conf
        %% Aallows 'dashboard' users to subscribe to '$SYS/#'
        {allow, {user, "dashboard"}, subscribe, ["$SYS/#"]}.

        %% Allows local user to publish and subscribe to all topics
        {allow, {ipaddr, "127.0.0.1"}, pubsub, ["$SYS/#", "#"]}.

        %% Deny all the users to subscribe to '$SYS/#' and '#' topics except local users
        {deny, all, subscribe, ["$SYS/#", {eq, "#"}]}.

        %% Allows any situation other than the above rules
        {allow, all}.

The authentication plugins provided by EMQ X include:

plugins             description
emqx_auth_clientid  ClientId authentication plugin
emqx_auth_username  username and password authentication plugin
emqx_auth_jwt   JWT authentication plugin
emqx_auth_ldap  LDAP authentication plugin
emqx_auth_http  HTTP authentication plugin
emqx_auth_mysql MySQ Lauthentication plugin
emqx_auth_pgsql Postgre authentication plugin
emqx_auth_redis Redis authentication plugin
emqx_auth_mongo MongoDB authentication plugin

2.3.7. 测试TLS

    mosquitto_sub -h 127.0.0.1 -p 8883 -d -t topic -q 2 -u ElonMusk -P password --psk 1234 --psk-identity client1
    mosquitto_pub -h 127.0.0.1 -p 8883 -d -t topic -q 2 -m "Hello TLS" -u Sender -P password --psk 1234 --psk-identity client1

3. EMQX消息服务器默认配置

  • TCP端口包括

    • 如果是云内主机,注意放开安全组等限制条件。
      1883    MQTT protocol port
      8883    MQTT/SSL port
      8083    MQTT/WebSocket port
      8084    MQTT/WebSocket SSL port
      8080    HTTP API port
      18083   Dashboard Management Console Port
  • 使用 mosquitto_sub/pub客户端命令行来订阅和发布消息

    //订阅消息并在后台监听
    mosquitto_sub -h 127.0.0.1 -p 1883 -t topic1 -q 2 &
    //发布消息
    mosquitto_pub -h 127.0.0.1 -p 1883 -t topic1 -q 1 -m ‘Hello, MQTT!’
  • 后台管理web端口

    #验证服务正常
    curl http://127.0.0.1:18083

  端口18083登录web进入管理端入口,默认用户: admin , 密码:public 。左侧管理边栏可以对EMQX设置,其中plugins可以管理插件,具体内容自行查看https://developer.emqx.io/docs/emq/v3/cn/plugins.html;可以用./bin/emqx_ctl plugins load 插件名字安装插件。记得修改密码

4. emqx提供了三种消息发布服务质量

  Quality of Service等级是发送与接收端的一种关于保证交付信息的协议。一共有3 个QoS 等级:

  • QoS 0:至多一次
    特点:消息发布完全依赖底层 TCP/IP 网络,不提供任何消息确认机制。发送方只负责将消息发送出去,不管接收方是否成功接收。因此,可能会发生消息丢失或者重复的情况。
    适用场景:适用于对消息丢失或重复不太敏感的场景,例如环境传感器数据的传输。因为传感器通常会频繁地发送数据,偶尔丢失一次数据对整体系统的影响不大,而且不久之后会有新的数据发送过来。
  • QoS 1:至少一次
    特点:发送方在发送消息后,会等待接收方的确认回执。如果没有收到确认,发送方会自动重发消息,直到收到确认或者达到最大重发次数。这就确保了消息至少会被接收方接收一次,但由于可能会重发,所以消息重复可能发生。
    适用场景:适用于需要确保消息到达,但对消息重复不太敏感的场景。例如,在一些监控系统中,偶尔收到重复的监控数据不会对系统造成严重影响,但必须保证重要的监控信息不会丢失。
  • QoS 2:只有一次
    特点:这是最高等级的 QoS,它确保消息只被接收方接收一次,不会丢失也不会重复。实现这个等级的保证需要更复杂的消息确认和去重机制。发送方和接收方会通过一系列的握手和确认过程来确保消息的准确传递。
    适用场景:适用于对消息准确性要求极高的场景,例如计费系统。在计费系统中,消息的重复或者丢失都可能导致不正确的计费结果,从而造成经济损失。

5. EMQ离线消息

  1. 保留消息 MQTT客户端向服务器发布(PUBLISH)消息时,可以设置保留消息(Retained Message)标志。保留消息(Retained Message)会驻留在消息服务器,后来的订阅者订阅主题时仍可以接收该消息。 例如mosquitto命令行发布一条保留消息到主题’a/b/c’: mosquitto_pub -r -q 1 -t a/b/c -m 'hello' 之后连接上来的MQTT客户端订阅主题’a/b/c’时候,仍可收到该消息: $ mosquitto_sub -t a/b/c -q 1 hello 保留消息(Retained Message)有两种清除方式: 客户端向有保留消息的主题发布一个空消息: mosquitto_pub -r -q 1 -t a/b/c -m '' 消息服务器设置保留消息的超期时间。

  2. cleanSession 清理回话 MQTT客户端向服务器发起CONNECT请求时,可以通过’Clean Session’标志设置会话。 ‘Clean Session’设置为0,表示创建一个持久会话,在客户端断开连接时,会话仍然保持并保存离线消息,直到会话超时注销。 ‘Clean Session’设置为1,表示创建一个新的临时会话,在客户端断开时,会话自动销毁。

6. 测试会话

  • MQTT的windows免费客户端下载MQTTX

6.1. 测试Username

```bash
cd /home/x/work/emqx-rel/_build/emqx/rel/emqx

add a user
    ./bin/emqx_ctl users add ElonMusk password

vim ./etc/emqx.conf
    allow_anonymous = false
enable plugins
    ./bin/emqx_ctl plugins list
    ./bin/emqx_ctl plugins load emqx_auth_username
restart emqx
    ./bin/emqx restart
    ./bin/emqx --help
    Usage: emqx {start|start_boot <file>|ertspath|foreground|stop|restart|reboot|pid|ping|console|console_clean|console_boot <file>|attach|remote_console|upgrade|escript|rpc|rpcterms|eval}

mosquitto_sub -h 127.0.0.1 -p 1883 -d -t topic -q 2 -u ElonMusk -P password
mosquitto_pub -h 127.0.0.1 -p 1883 -d -t topic -q 2 -m "Hello, Username!" -u ElonMusk -P password
```
赞赏

微信赞赏支付宝赞赏

发表评论

邮箱地址不会被公开。 必填项已用*标注