1.MQTT协议概述
MQTT是一种基于发布/订阅模式的轻量级消息传输协议,常用于低带宽、不可靠网络环境下传输消息,适用于物联网设备之间的通信。
1.1 MQTT协议的组件
- 客户端(Client):连接到MQTT代理服务器的设备(发布者、订阅者)
- 代理服务器(Broker):负责接收来自客户端的消息并将其转发给订阅该主题的客户端
- 主题(Topic):消息的分类标识,客户端通过订阅或发布到特定主题来接受或发送消息
- 消息(Message):客户端通过主题传输的数据负载
客户端通过TCP/IP连接到代理,通过身份验证保持长连接
2.MQTT服务器搭建
用EMQX来搭建服务器
快速开始 | EMQX 4.3 文档https://docs.emqx.com/zh/emqx/v4.3/getting-started/getting-started.html 下载EMQX
https://www.emqx.com/zh/try?product=brokerhttps://www.emqx.com/zh/try?product=broker 安装虚拟机(环境:centOS7)
配置 EMQX Yum 源
curl -s https://assets.emqx.com/scripts/install-emqx-rpm.sh | sudo bash
安装依赖
yum install epel-release -y
yum install -y openssl11 openssl11-devel
安装 EMQX
sudo yum install emqx -y
启动 EMQX
sudo systemctl start emqx
访问管理后台:http://localhost:18083/#/login?to=/dashboard/overview
(默认用户名:admin 密码:public)
访问接口文档: http://localhost:18083/api-docs/index.html#
2.1 创建主题
3.使用EMQX服务器
3.1 导入依赖
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.2</version>
</dependency>
3.2 创建MQTT连接
String broker = "tcp://localhost:1883";
// TLS/SSL
// String broker = "ssl://broker.emqx.io:8883";
String username = "emqx";
String password = "public";
String clientid = "publish_client";
MqttClie