
一介闲人
一介闲人
首先,需要安装EPEL(Extra Packages for Enterprise Linux)仓库,因为Mosquitto不在CentOS默认的仓库中。
sudo yum install epel-release
安装完EPEL仓库后,通过yum来安装Mosquitto。
sudo yum install mosquitto mosquitto-clients
这个命令会安装Mosquitto服务器和客户端工具。
安装完成后,启动Mosquitto服务。
sudo systemctl start mosquitto
为了让Mosquitto在系统启动时自动运行,需要设置为开机自启。
sudo systemctl enable mosquitto
检查Mosquitto服务的状态,确保它正在运行。
sudo systemctl status mosquitto
安装完Mosquitto后,使用mosquitto_pub和mosquitto_sub命令来测试消息的发布和订阅功能。
发布消息(Publisher):
mosquitto_pub -h localhost -t "test/topic" -m "Hello MQTT"
这里-h指定了MQTT服务器的地址,-t指定了主题(Topic),-m是要发布的消息内容。
订阅消息(Subscriber): 在另一个终端中,你可以订阅刚才发布的主题来接收消息。
mosquitto_sub -h localhost -t "test/topic" -v
这里-v选项表示显示接收到的消息的详细信息。
Mosquitto的配置文件通常位于/etc/mosquitto/mosquitto.conf。根据需要编辑这个文件来配置认证、持久化、监听端口等高级功能。例如,要允许非本地连接,可以取消注释或添加以下行:
listener 1883 0.0.0.0
修改配置后,重启Mosquitto服务:
sudo systemctl restart mosquitto
编辑Mosquitto配置文件(通常位于/etc/mosquitto/mosquitto.conf)来启用用户名和密码验证
vim /etc/mosquitto/mosquitto.conf
在文件中找到或添加以下行来启用密码文件和使用持久会话:
allow_anonymous false
password_file /etc/mosquitto/passwd
persistence true
persistence_location /var/lib/mosquitto/
保存并关闭文件。
创建一个密码文件,Mosquitto将使用这个文件来验证用户名和密码。
mosquitto_passwd -c /etc/mosquitto/passwd <username>
在上面的命令中,将
重启Mosquitto服务:
sudo systemctl restart mosquitto
验证配置
启用接收消息
mosquitto_sub -h localhost -t "test/topic" -v -u <username> -P <password>
启用发送消息
mosquitto_pub -h localhost -t "test/topic" -u <username> -P <password> -m "Hello MQTT"
替换
1、如何清除保留消息?
答:发送一条空的保留消息即可清除
mosquitto_pub -h localhost -u <username> -P <password> -t "your/topic" -n -r
评论