一文读懂物联网 MQTT 协议之实战篇

article/2025/11/5 13:33:27

一、前言

上一篇我们介绍了 MQTT 协议格式以及相关的特性:一文读懂物联网 MQTT 协议之基础特性篇,这一篇我们就来实战一番,理论得与实践结合,方能吃透 MQTT。

我的那个读者还提到了讲一下 Mosquitto,这是一款开源消息代理软件,提供轻量级的,支持可发布/可订阅的的消息推送模式,使设备对设备之间的短消息通信变得简单,比如现在应用广泛的低功耗传感器,手机、嵌入式计算机、微型控制器等移动设备。

老周这就来带大家在 CentOS 上搭建 Mosquitto 服务器。

二、搭建准备

Mosquitto 安装版本:Mosquitto1.4.4
Mosquitto 各版本下载地址:https://mosquitto.org/files/source/
MQTT 协议参考网站:MQTT 3.1.1
libwebsockets下载地址:https://github.com/warmcat/libwebsockets/releases
CentOS 版本:CentOS 7.8.2003
在这里插入图片描述

2.1 软件准备

从官网获取安装包:

wget http://mosquitto.org/files/source/mosquitto-1.4.14.tar.gz

2.2 安装

tar -zxvf mosquitto-1.4.14.tar.gz
cd mosquitto-1.4.14

2.3 修改配置文件

config.mk 包括了多个选项, 可按需关闭或开启,但一旦开启则需要先安装对应的模块。

vim config.mk
选项说明make时的出错信息
WITH_SRV启用c-areas库的支持,一个支持异步DNS查找的库,见http://c-ares.haxx.semissing ares.h
WITH_UUID启用lib-uuid支持,支持为每个连接的客户端生成唯一的uuid。missing uuid.h
WITH_WEBSOCKETS启用websocket支持,需安装libwebsockets,对于需要使用websocket协议的应用开启。missing libwebsockets.h
WITH_SRV:=yes
WITH_UUID:=yes
WITH_WEBSOCKETS:=yes

2.3.1 安装 c-areas

yum install c-ares-devel -y

2.3.2 安装 lib-uuid

yum install uuid-devel -y
yum install libuuid-devel -y

2.3.3 安装 libwebsockets

cd ~
wget https://github.com/warmcat/libwebsockets/archive/v3.2.1.tar.gz
tar zxvf v3.2.1.tar.gz
cd libwebsockets-3.2.1
mkdir build
cd build
cmake .. -DLIB_SUFFIX=64
make install
ldconfigcd mosquitto-1.4.14
yum install openssl-devel -y

2.4 编译和安装

make && make install

执行编译 make 命令的时候,如果你的终端出现:

在这里插入图片描述
那就把把 WITH_WEBSOCKETS 从 yes 改成 no 后,就可以成功编译了。

WITH_WEBSOCKETS:=yes
改成
WITH_WEBSOCKETS:=no

如果你的应用不需要 websocket 协议,可以把这个参数给设置 no 关掉。

如果终端出现的是这样:

在这里插入图片描述
那么恭喜你,Mosquitto 安装成功了。

2.5 说明

程序文件将默认安装到以下位置

路径程序文件
/usr/local/sbinmosquiotto server
/etc/mosquittoconfiguration
/usr/local/binutility command

修正链接库路径

由于操作系统版本及架构原因,很容易出现安装之后的链接库无法被找到,如启动 mosquitto 客户端可能出现找不到 libmosquitto.so.1 文件,因此需要添加链接库路径:

vim /etc/ld.so.conf.d/liblocal.conf

在文件中添加以下内容:

/usr/local/lib64
/usr/local/lib
# 刷新
ldconfig

三、 Mosquitto Server 启动与测试

3.1 启动

3.1.1 mosquitto 默认以 mosquitto 用户启动

可以通过配置文件修改,需添加用户:

groupadd mosquitto
useradd -g mosquitto mosquitto

3.1.2 修改配置文件

mv /etc/mosquitto/mosquitto.conf.example /etc/mosquitto/mosquitto.conf
# =================================================================
# General configuration
# =================================================================
# 客户端心跳的间隔时间
#retry_interval 20
# 系统状态的刷新时间
#sys_interval 10
# 系统资源的回收时间,0表示尽快处理
#store_clean_interval 10
# 服务进程的PID
#pid_file /var/run/mosquitto.pid
# 服务进程的系统用户
#user mosquitto
# 客户端心跳消息的最大并发数
#max_inflight_messages 10
# 客户端心跳消息缓存队列
#max_queued_messages 100
# 用于设置客户端长连接的过期时间,默认永不过期
#persistent_client_expiration
# =================================================================
# Default listener
# =================================================================
# 服务绑定的IP地址
#bind_address
# 服务绑定的端口号
#port 1883
# 允许的最大连接数,-1表示没有限制
#max_connections -1
# cafile:CA证书文件
# capath:CA证书目录
# certfile:PEM证书文件
# keyfile:PEM密钥文件
#cafile
#capath
#certfile
#keyfile
# 必须提供证书以保证数据安全性
#require_certificate false
# 若require_certificate值为true,use_identity_as_username也必须为true
#use_identity_as_username false
# 启用PSK(Pre-shared-key)支持
#psk_hint
# SSL/TSL加密算法,可以使用“openssl ciphers”命令获取
# as the output of that command.
#ciphers
# =================================================================
# Persistence
# =================================================================
# 消息自动保存的间隔时间
#autosave_interval 1800
# 消息自动保存功能的开关
#autosave_on_changes false
# 持久化功能的开关
persistence true
# 持久化DB文件
persistence_file mosquitto.db
# 持久化DB文件目录
persistence_location /var/lib/mosquitto/
# =================================================================
# Logging
# =================================================================
# 4种日志模式:stdout、stderr、syslog、topic
# none 则表示不记日志,此配置可以提升些许性能
log_dest none
# 选择日志的级别(可设置多项)
#log_type error
#log_type warning
#log_type notice
#log_type information
# 是否记录客户端连接信息
#connection_messages true
# 是否记录日志时间
#log_timestamp true
# =================================================================
# Security
# =================================================================
# 客户端ID的前缀限制,可用于保证安全性
#clientid_prefixes
# 允许匿名用户
#allow_anonymous true
# 用户/密码文件,默认格式:username:password
#password_file
# PSK格式密码文件,默认格式:identity:key
#psk_file
# pattern write sensor/%u/data
# ACL权限配置,常用语法如下:
# 用户限制:user <username>
# 话题限制:topic [read|write] <topic>
# 正则限制:pattern write sensor/%u/data
#acl_file
# =================================================================
# Bridges
# =================================================================
# 允许服务之间使用“桥接”模式(可用于分布式部署)
#connection <name>
#address <host>[:<port>]
#topic <topic> [[[out | in | both] qos-level] local-prefix remote-prefix]
# 设置桥接的客户端ID
#clientid
# 桥接断开时,是否清除远程服务器中的消息
#cleansession false
# 是否发布桥接的状态信息
#notifications true
# 设置桥接模式下,消息将会发布到的话题地址
# $SYS/broker/connection/<clientid>/state
#notification_topic
# 设置桥接的keepalive数值
#keepalive_interval 60
# 桥接模式,目前有三种:automatic、lazy、once
#start_type automatic
# 桥接模式automatic的超时时间
#restart_timeout 30
# 桥接模式lazy的超时时间
#idle_timeout 60
# 桥接客户端的用户名
#username
# 桥接客户端的密码
#password
# bridge_cafile:桥接客户端的CA证书文件
# bridge_capath:桥接客户端的CA证书目录
# bridge_certfile:桥接客户端的PEM证书文件
# bridge_keyfile:桥接客户端的PEM密钥文件
#bridge_cafile
#bridge_capath
#bridge_certfile
#bridge_keyfile

关于详细配置可参考:http://mosquitto.org/man/mosquitto-conf-5.html

3.1.3 设置用户名和密码

将配置文件中 #allow_anonymous true 去掉注释,设置为 false#password_file 去掉注释并添加密码文件保存的位置:

allow_anonymous false
password_file /etc/mosquitto/pwfile.example
mosquitto_passwd -c /etc/mosquitto/pwfile.example 用户名
之后需输入两次密码
注意如果想添加用户
mosquitto_passwd -b /etc/mosquitto/pwfile.example 用户名 密码

同样连续会提示连续输入两次密码。注意第二次创建用户时不用加 -c 如果加 -c 会把第一次创建的用户覆盖。

3.1.4 启动 mosquitto

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

成功将启动并监听 1883 端口

3.2 测试

新建两个 shell 窗口 A/B

A 订阅主题:

mosquitto_sub -t 主题名 -h 主机IP -u 用户名 -P 密码
例如:mosquitto_sub -t topic-riemann -h localhost -u mosquitto -P mosquitto

B 推送消息:

mosquitto_pub -t 主题名 -h 主机IP -m "消息内容" -u 用户名 -P 密码
例如:mosquitto_pub -t topic-riemann -h localhost -m "hello,mqtt" -u mosquitto -P mosquitto

3.3 可能遇到的问题

如果你出现这个错误:

mosquitto_sub: error while loading shared libraries: libmosquitto.so.1: cannot open shared object file: No such file or directory

解决方法:

编译完 mosquitto 之后,进入到 lib 目录下,将编译之后的 libmosquitto.so.1 拷贝到目录 /usr/local/lib下,执行如下命令:

cp libmosquitto.so.1 /usr/local/lib

然后再执行命令:

sudo ln -s /usr/local/lib/libmosquitto.so.1 /usr/lib/libmosquitto.so.1
ldconfig

3.4 测试结果

在这里插入图片描述
在这里插入图片描述

四、Java 实现 Mosquitto 客户端

4.1 项目结构图

在这里插入图片描述

4.2 添加 pom.xml

<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.6.RELEASE</version>
</parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.integration</groupId><artifactId>spring-integration-mqtt</artifactId><version>5.2.5.RELEASE</version></dependency>
</dependencies>

4.3 application.yml

mqtt:host: tcp://服务器IP:1883clientId: client_${random.value}topic: test/system/module/bizqoslevel: 1username: mosquittopassword: mosquittotimeout: 10000keepalive: 20server:port: 8888

4.4 MqttConfig

/*** @author: 微信公众号【老周聊架构】*/
@Slf4j
@Configuration
@IntegrationComponentScan
public class MqttConfig {@Value("${mqtt.username}")private String username;@Value("${mqtt.password}")private String password;@Value("${mqtt.host}")private String hostUrl;@Value("${mqtt.clientId}")private String clientId;@Value("${mqtt.topic}")private String defaultTopic;// 连接超时@Value("${mqtt.timeout}")private int completionTimeout;@Beanpublic MqttConnectOptions getMqttConnectOptions() {MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();mqttConnectOptions.setCleanSession(true);mqttConnectOptions.setConnectionTimeout(10);mqttConnectOptions.setKeepAliveInterval(90);mqttConnectOptions.setAutomaticReconnect(true);mqttConnectOptions.setUserName(username);mqttConnectOptions.setPassword(password.toCharArray());mqttConnectOptions.setServerURIs(new String[]{hostUrl});mqttConnectOptions.setKeepAliveInterval(2);return mqttConnectOptions;}@Beanpublic MqttPahoClientFactory mqttClientFactory() {DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();factory.setConnectionOptions(getMqttConnectOptions());return factory;}@Bean@ServiceActivator(inputChannel = "mqttOutboundChannel")public MessageHandler mqttOutbound() {MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(clientId, mqttClientFactory());messageHandler.setAsync(true);messageHandler.setDefaultTopic(defaultTopic);return messageHandler;}@Beanpublic MessageChannel mqttOutboundChannel() {DirectChannel directChannel = new DirectChannel();return directChannel;}// 接收通道@Beanpublic MessageChannel mqttInputChannel() {DirectChannel directChannel = new DirectChannel();return directChannel;}// 配置client,监听的topic@Beanpublic MessageProducer inbound() {MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(clientId + "_inbound",mqttClientFactory(), "test/#");adapter.setCompletionTimeout(completionTimeout);adapter.setConverter(new DefaultPahoMessageConverter());adapter.setQos(1);adapter.setOutputChannel(mqttInputChannel());return adapter;}// 通过通道获取数据@Bean@ServiceActivator(inputChannel = "mqttInputChannel")public MessageHandler handler() {return message -> {String topic = (String)message.getHeaders().get("mqtt_receivedTopic");log.info("主题:{},消息接收到的数据:{}", topic, message.getPayload());};}
}

4.5 MqttGateWay

/*** @author: 微信公众号【老周聊架构】*/
@MessagingGateway(defaultRequestChannel = "mqttOutboundChannel")
public interface MqttGateWay {// 定义重载方法,用于消息发送void sendToMqtt(String payload);// 指定topic进行消息发送void sendToMqtt(@Header(MqttHeaders.TOPIC) String topic, String payload);void sendToMqtt(@Header(MqttHeaders.TOPIC) String topic, @Header(MqttHeaders.QOS) int qos, String payload);
}

4.6 MqttController 控制类

/*** @author: 微信公众号【老周聊架构】*/
@Slf4j
@RestController
@RequestMapping("/api")
public class MqttController {@AutowiredMqttGateWay mqttGateWay;@PostMapping("/publish")public String publish(@RequestHeader(value = "toplic") String toplic , String message) {log.info(String.format("topic: %s, message: %s", toplic, message));mqttGateWay.sendToMqtt(toplic, message);return "success";}
}

4.7 MqttApplication 启动类

/*** @author: 微信公众号【老周聊架构】*/
@SpringBootApplication
public class MqttApplication {public static void main(String[] args) {SpringApplication.run(MqttApplication.class, args);}
}

4.8 启动 mosquitto 服务器

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

4.9 利用 IDEA 的 HTTP Client 模拟 HTTP 请求

在这里插入图片描述
在这里插入图片描述
4.10 测试结果

IDEA 控制台接收到该主题的消息:
在这里插入图片描述
shell 终端显示也收到了订阅了该主题的消息:

在这里插入图片描述


http://chatgpt.dhexx.cn/article/MvkTq8G1.shtml

相关文章

基于光流传感器定位和导航的自主飞行无人机

基于光流传感器定位和导航的自主飞行无人机 An Autonomous UAV with an Optical Flow Sensor for Positioning and Navigation 注&#xff1a;翻译水平有限&#xff0c;错误之处&#xff0c;敬请指正&#xff01; 原文链接&#xff1a;http://cdn.intechopen.com/pdfs/45731.p…

Kubernetes NetworkPolicy:打造更安全的容器运行环境

常见的应用可以分为两大类&#xff1a;Job和Service。Job比较简单&#xff0c;就是一个普通的任务&#xff0c;完成之后就退出&#xff0c;一般不需要暴露对外服务的网络监听端口。Service是指长期运行的进程&#xff0c;监听某个网络端口&#xff0c;其他服务可以通过网络连过…

Drupal远程代码执行漏洞(CVE-2018-7600)

目录 一. 漏洞原理 二. 影响版本 三. 漏洞环境搭建 四. 漏洞复现 一. 漏洞原理 Drupal是一个开源内容管理系统&#xff08;CMS&#xff09;&#xff0c;全球超过100万个网站&#xff08;包括政府&#xff0c;电子零售&#xff0c;企业组织&#xff0c;金融机构等&#xff0…

记一次从盲SSRF到RCE

公粽号&#xff1a;黒掌 一个专注于分享网络安全、黑客圈热点、黑客工具技术区博主&#xff01; 一 前言 发现此漏洞的漏洞赏金计划不允许公开披露&#xff0c;因此我不会直接使用涉及的系统名称。该项目是发布在Hackerone时间最长漏洞奖金最大的项目之一, Hackerone上有很多关…

002.光流传感器(ADNS0380版)使用说明

先放广告&#xff0c;以下是光流传感器购买地址&#xff08;全网最低价并且唯一提供代码支持的&#xff09;&#xff1a; https://item.taobao.com/item.htm?spma230r.1.14.63.j2eDn3&id541014211123&ns1&abbucket12#detail 如果模块直接使用在APM飞控上请看下文标…

003.关于光流传感器(ADNS3080)调焦问题

关于光流传感器使用官方网址如下&#xff1a; http://ardupilot.org/copter/docs/common-mouse-based-optical-flow-sensor-adns3080.html 微信公众号&#xff1a;嵌入式大玩家 更多精彩文章我将第一时间在微信公众号里面分享&#xff0c;如果不想错过,可以关注我的微信公众号。…

腾讯笔试题——逆序对

这题花了我非常多时间&#xff0c;ac率从10&#xff05; --> 50&#xff05; --> 60&#xff05; --> 70&#xff05; --> 80&#xff05; --> 100&#xff05; &#xff0c;被这题疯狂支配几个小时&#xff01; 最关键没有详细的题解可以参考&#xff0c;大数据…

2020秋招腾讯后台笔试题(一)

点击上方蓝字设为星标 下面开始今天的学习&#xff5e; 这是2020届腾讯秋招的笔试题&#xff0c;其实就是19年九月份的题目&#xff0c;总共五道题&#xff0c;这篇文章写说两道题&#xff0c;都是有关于栈的应用的 01 压缩算法 小Q想要给他的朋友发送一个神秘字符串&#xff0…

腾讯笔试-1

1、什么是运维&#xff1f;什么是游戏运维&#xff1f;1&#xff09;运维是指大型组织已经建立好的网络软硬件的维护&#xff0c;就是要保证业务的上线与运作的正常&#xff0c;在他运转的过程中&#xff0c;对他进行维护&#xff0c;他集合了网络、系统、数据库、开发、安全、…

腾讯 C++ 笔试/面试题及答案

星标/置顶 公众号&#x1f447;&#xff0c;硬核文章第一时间送达&#xff01; 链接 | https://zhuanlan.zhihu.com/p/274473971 题很多&#xff0c;先上题后上答案&#xff0c;便于大家思考 问题点&#xff1a; 1、C和C的特点与区别&#xff1f; 2、C的多态 3、虚函数实现 4、…

腾讯2020校园招聘笔试

输入1&#xff1a; 2 2 1 1 1 1 输出1&#xff1a; 0 输入2&#xff1a; 2 2 1 2 2 1 输出2&#xff1a; 2 import java.util.Scanner; public class Main { public static void main(String[] args) {// TODO Auto-generated method stubScanner scnew Scanner(Syste…

腾讯笔试题20210321

一、链表树 时间限制&#xff1a;C/C 1秒&#xff0c;其他语言 2秒 空间限制&#xff1a;C/C 262144K&#xff0c;其他语言 524288K 64bit IO Format: %lld 题目描述 在牛牛所在的世界&#xff0c;链表是一种二叉树。 这是牛牛第一次见到链表树&#xff0c;他感到十分好奇&a…

腾讯2021批笔试题解

总结&#xff1a;一套算是正常的笔试…算是让大家有点思考了…都没那么一眼秒&#xff08;除了强烈谴责某T5最短路板子。我还差点没看到这题hhh&#xff08;&#xff08; &#xff08;另一套题的T5&#xff09; T5 题目大意&#xff1a;给出n个红球&#xff0c;n个黑球&#x…

腾讯笔试题精选一

1.32位机上根据下面的代码&#xff0c;问哪些说法是正确的&#xff1f;&#xff08;&#xff09; signed char a 0xe0 unsigned int b a; unsigned char c a; A. a>0 && c>0 为真 B.a c 为真 C.b的十六进制表示是&#xff1a;0xfffffe0 D.上面都不对 sig…

腾讯笔试题_20220424

前言 笔试一共五道编程题&#xff0c;满分是100分&#xff0c;时间是两个小时&#xff0c;可以跳题&#xff0c;使用的平台是牛客网&#xff0c;允许跳出界面使用本地IDE。 题目一&#xff1a;构建数字 给定n个长度均为m的数字字符串&#xff0c;从上往下构建成m个新的数&am…

笔试面试(1)腾讯2014校园招聘软件开发类笔试试题

把基本经典的书籍认真看看,那些笔试面试的都不是什么问题。但是,专门的突击和训练还是很有必要的。 好的offer是可以通过充分的准备刷到的。 我们就从各大公司的套题开始刷起吧,中间再穿插一些专题。 今天先看看腾讯的2014年校招的软开笔试题。 考试时长:120分钟 一 不定项…

腾讯近三年软件测试工程师面试笔试题目精选(包含答案)

目录 1、什么是兼容性测试?兼容性测试侧重哪些方面? 2、我现在有个程序&#xff0c;发现在 Windows 上运行得很慢&#xff0c;怎么判别是程序存在问题 还是软硬件系统存在问题? 3、测试的策略有哪些? 4、正交表测试用例设计方法的特点是什么? 5、描述使用 bugzilla 缺…

Dev ChartControl 显示设置百分比

**Dev ChartControl 显示设置百分比**//Y轴设置成百分数显示((XYDiagram)Chart.Diagram).AxisY.Label.TextPattern "{V:0%}";//显示的值为百分数 for (int j 0; j < Chart.Series.Count; j){Series march Chart.Series[j];march.CrosshairLabel…

DevExpress——ChartControl知多少(C#)

目前在做的这个项目后端是使用.NET框架在做,前端是借助DevExpress框架做开发,由于是基于Winform的页面实现,于是DevExpress提供了全套的Winform的解决方案,弥补了Winform本身的工具箱不全且不再维护的弊端。DevExpress提供的表图控件叫做ChartControl,在其上面可以完成图表…