自建 MQTT 服务器过程

因需要通过网络提供对硬件的可控测试要求,下面详细记录在阿里云ECS上搭建MQTT服务的过程。

目前可使用的MQTT服务端Broker(消息代理)有许多。经查询对比,选择Mosquitto为此次测试的Broker。

其他的Broker及其特点可以前往下面地址详细阅读。

SoftwareA collection of links to all important MQTT brokers/servers, MQTT client libraries, tools and plugins.icon-default.png?t=N7T8https://mqtt.org/software/

 Tips:测试ECS上系统为Debian 12。 

1、更新Debian软件仓库

# apt update

2、安装消息代理(broker)服务端软件包,也就是 mosquitto 软件包

# apt install mosquitto

安装完毕后,该软件已自行启动

3、检查 mosquitto 运行服务状态

# service mosquitto status

下面为相关操作。

# service mosquitto status         //状态查询操作

# service mosquitto start           //开启服务

# service mosquitto stop           //停止服务

# service mosquitto restart        //重启服务

# service mosquitto --help        //命令使用帮助

4、 配置mosquitto 

相关配置文件都在/etc/mosquitto目录及其子目录下,

主配置文件为mosquitto.conf,完整配置情况参见 /usr/share/doc/mosquitto/examples/mosquitto.conf.example 文件

进入/etc/mosquittomo目录,使用 vim 或 nano 编辑mosquitto.conf,添加下列字符行

# 不允许匿名

allow_anonymous false

# 指定用户密码存储文件

password_file /etc/mosquitto/pw_file

# 指定主题(topic)与用户关联的文件

acl_file /etc/mosquitto/acl

 5、创建用户信息文件 pw_file,并添加新用户 tester 

# mosquitto_passwd -c /etc/mosquitto/pw_file tester

命令行中的 tester 为任意字符,其表示将来需要订阅或发布消息的用户名。

该命令将在 /etc/mosquito 目录中创建名为 pw_file 的文件,将用户名(tester)和密码写到文件中,用户名是明文,密码是加密过的密文。

6、添加用户与消息主题(Topic)的关系

# vim /etc/mosquitto/acl_file

添加以下字符内容

user tester                      // tester 是前面已添加的用户名
topic write MyTopic/#      // MyTopic 是主题名,write 关键词表示用户对名为MyTopic的主题可写

user tester                      // tester 是前面已添加的用户名
topic write MyTopic/#     // MyTopic 是主题名,read 关键词表示用户对名为MyTopic的主题可读

7、 重启mosquitto服务

直接重启Broker服务,mosquitto将自动加载默认配置文件( /etc/mosquitto/mosquitto.conf )

# service mosquitto restart

也可以让 mosquitto 启动/重启 时加载指定的配置文件,如名为 xxxxx 文件

# service mosquitto restart -c /etc/mosquitto/xxxxx -d

用法参见  # mosquitto --help

 8、 安装mosquitto客户端软件包以便进行消息发布测试

# apt install mosquitto-client

9、在服务器上,使用 mosquitto 客户工具 mosquitto_sub 连接 Broker 并 订阅 消息

# mosquitto_sub -h localhost -t MyTopic -u tester -P xxxxx

10、在服务器上新开一个终端,使用 mosquitto 客户工具 mosquitto_pub 连接 Broker 并 发布 消息。

# mosquitto_pub -h localhost -t MyTopic -u tester -P xxxxx -m "Hello,MQTT"

-h  Broker服务器地址

-t  消息主题

-u  用户名

-P  用户密码

-m 发布的消息内容

详细用法参照 # mosquitto_pub --help 及  # mosquitto_sub --help

 

  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值