MQTT协议是广泛应用的物联网协议(https://mqtt.org/),使用测试MQTT协议需要MQTT的代理。有两种方法使用MQTT服务,一是租用现成的MQTT服务器,如阿里云,百度云,华为云等公用的云平台提供的MQTT服务,使用公用的MQTT服务器的好处是省事,但如果仅仅用于测试学习还需要注册帐号,灵活性差些,有的平台还需要付费。另一方法是自己使用开源的MQTT组件来搭建mqtt服务器。

MQTT服务器开源的程序非常多,例如:Mosquitto、apache的ActiveMQ、emtqqd、HiveMQ、Emitter、Mosquitto、Moquette等等。

本文这里重点介绍的是用轻量级的mosquitto开源项目来搭建一个属于自己的MQTT服务器。

一、用 Mosquitto搭建一个属于自己的MQTT服务器教程

Mosquitto轻巧,适合在从低功耗单板计算机到完整服务器的所有设备上使用。

Mosquitto项目还提供了一个用于实现MQTT客户端的C库,以及非常流行的mosquitto_pub和mosquitto_sub命令行MQTT客户端。

1、Linux下环境准备

yum install libc-ares-dev 
yum install libuuid-devel 
yum install gcc 
yum install gcc-c++

2、Mosquitto下载、安装

wget https://mosquitto.org/files/source/mosquitto-2.0.14.tar.gz
tar zxfv mosquitto-2.0.14.tar.gz
cd mosquitto-2.0.14
make && make instal

3、启动 mosquitto

这时候mosquitto就会以默认的参数启动。

mosquitto -v

4、发布与订阅

发布使用mosquitto_pub命令,订阅使用mosquitto_sub命令。常用参数介绍:

java mqtt开源服务端 开源mqtt服务器搭建_java mqtt开源服务端

#订阅主题 testtopic
mosquitto_sub -h 127.0.0.1 -p 1883 -v -t testtopic
#发布消息helloword到主题testtopic
mosquitto_pub -h 127.0.0.1 -p 1883 -t testtopic -m helloworld

这时候我们的MQTT服务器就算是搭建好了。但还不是很完美,因为Mosquitto服务器大部分都是采用默认的是允许匿名用户登录模式,还有就是权限什么的?因此,需要继续往下看:

二、Mosquitto 配置 详细教程

1、主配置文件:mosquitto.conf

Mosquitto服务器的配置文件路径一般为:/etc/mosquitto/mosquitto.conf,内容一般如下:

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
# 禁止匿名访问
allow_anonymous false
# 认证配置
password_file /etc/mosquitto/pwfile
# 权限配置
acl_file /etc/mosquitto/aclfile

2、认证配置文件:pwfile

如果没有则创建文件,用命令:

touch /etc/mosquitto/pwfile

添加新用户:

服务开启后,输入如下命令,根据提示输入两遍密码:

mosquitto_passwd /etc/mosquitto/pwfile 用户名

3、权限配置文件:aclfile

打开文件

vim /etc/mosquitto/aclfile

编辑内容

# A发布以test为前缀的主题,订阅以$SYS开头的主题即系统主题
user A
topic write test/#
topic read $SYS/#
# B订阅以test为前缀的主题
user B
topic read test/#

4、启动

-c:指定特定配置文件启动

-d:后台运行

mosquitto -c /etc/mosquitto/mosquitto.conf -d

5、验证

java mqtt开源服务端 开源mqtt服务器搭建_配置文件_02

java mqtt开源服务端 开源mqtt服务器搭建_SYS_03