1.pom依赖
<!--mqtt-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-integration</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-stream</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-mqtt</artifactId>
</dependency>
2.application.yaml配置
hostUrl :mqtt服务所在ip和对应端口号(我的是emqx)
username和password测试demo可以随便填,线上环境肯定关闭了匿名访问,需要特定的用户名和密码
clientId:可以随便设置,但是对于一个mqtt服务需要避免重复的id,不然会出问题
topic:此处可以配置多个,然后订阅时候取出,循环订阅
spring:
mqtt:
username: username # 用户名
password: password # 密码
hostUrl: tcp://192.168.1.111:1883 # tcp://ip:端口
clientId: cloud # 客户端id
defaultTopic: d2c/message/#,device/response/#
timeout: 100 # 超时时间 (单位:秒)
keepalive: 60 # 心跳 (单位:秒)
enabled: true # 是否使能mqtt功能
3.代码块
1.MqttConfig
此部分是为了项目启动时候连接mqtt服务的(emqx)我使用的mqtt服务是emqx
package com.xinhuan.llpr.cloud.mqtt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
/**
* @author mlcheng
* @date 2022/8/5 10:01
*/
@Component
@ConfigurationProperties("spring.mqtt")
public class MqttConfig {
@Autowired
private MqttPushClient mqttPushClient;
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 连接地址
*/
private String hostUrl;
/**
* 客户Id
*/
private String clientId;
/**
* 默认连接话题
*/
private String defaultTopic;
/**
* 超时时间
*/
private int timeout;
/**
* 保持连接数
*/
private int keepalive;
/**
* mqtt功能使能
*/
private boolean enabled;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {