1、引入mqtt依赖
<!--springboot mqtt-->
<dependency>
<groupId>net.dreamlu</groupId>
<artifactId>mica-mqtt-client-spring-boot-starter</artifactId>
<version>2.2.6</version>
</dependency>
2、实现ApplicationRunner类
import net.dreamlu.iot.mqtt.spring.client.MqttClientTemplate;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
@Component
public class Demo implements ApplicationRunner {
@Resource
private MqttClientTemplate mqttTemplate;
@Override
public void run(ApplicationArguments args) throws Exception {
while (true) {
String msg = "解析后的坐标!";
mqttTemplate.publish("beidou/position", msg.getBytes(StandardCharsets.UTF_8));
Thread.sleep(1000);
}
}
}
3、yml添加mqtt配置
# mqtt
mqtt:
# 客户端
client:
# 是否开启客户端,默认:true
enabled: true
# 连接的服务端 ip ,默认:127.0.0.1
ip: broker.emqx.io
# 端口:默认:1883
port: 1883
# 名称,默认:Mica-Mqtt-Client
name: beidou-mqtt-client
# 客户端Id(非常重要,一般为设备 sn,不可重复)
clientId: ${mqtt.client.name}-${random.value}
# 认证的用户名
user-name: emqx
# 认证的密码
password: public
# 超时时间,单位:秒,默认:5秒
timeout: 5
# 是否重连,默认:true
reconnect: true
# 重连时间,默认 5000 毫秒
re-interval: 5000
# mqtt 协议版本,可选 MQTT_3_1、mqtt_3_1_1、mqtt_5,默认:mqtt_3_1_1
version: mqtt_3_1_1
# 接收数据的 buffer size,默认:8k
read-buffer-size: 8KB
# 消息解析最大 bytes 长度,默认:10M
max-bytes-in-message: 10MB
# 堆内存和堆外内存,默认:堆内存
buffer-allocator: heap
# keep-alive 时间,单位:秒
keep-alive-secs: 60
# mqtt clean session,默认:true
clean-session: true
ssl:
# 是否开启 ssl 认证,2.1.0 开始支持双向认证
enabled: false
# 可选参数:ssl 双向认证 keystore 目录,支持 classpath:/ 路径。
keystore-path:
# 可选参数:ssl 双向认证 keystore 密码
keystore-pass:
# 可选参数:ssl 双向认证 truststore 目录,支持 classpath:/ 路径。
truststore-path:
# 可选参数:ssl 双向认证 truststore 密码
truststore-pass:
4、本地安装mqtt服务
参考地址:https://blog.youkuaiyun.com/weixin_41542513/article/details/134328627
4、下载MQTTX客户端进行测试
MQTTX:https://mqttx.app/zh