前言:
关于整合mqtt网上的教程很多,本文是参考网上并结合自己实践写的教程笔记,本文参考成分很大,目的是为了以后自己使用时方便查找,文末贴出参考链接。
步骤很简单:
一、首先第一步,在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>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
二、第二步,yml文件增加如下
spring:
mqtt:
username: admin # 用户名
password: admin123 # 密码
hostUrl: tcp://xxx.xxx.xxx.xxx:1883 # tcp://ip:端口
clientId: ClientId_local # 客户端id 必须唯一 比如你已经定了叫ABC 那你就一直叫ABC 其他地方就不要使用ABC了
defaultTopic: test #MQTT-默认的消息推送主题,实际可在调用接口时指定 多个主题逗号分隔
timeout: 100 # 超时时间 (单位:秒)
keepalive: 60 # 心跳 (单位:秒)
三、第三步,我们需要加入4个类
分别是
配置类:MqttConfig
发布连接类:MqttPushClient
订阅类:MqttSubClient
回调类:PushCallback
1.配置类:
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;
import java.util.List;
/**
* 配置类
* @author cls
* @date 2024-8-19 11:00:00
*/
@Component
@ConfigurationProperties("spring.mqtt")
public class MqttConfig {
@Autowired
private MqttPushClient mqttPushClient;
@Autowired
private MqttSubClient mqttSubClient;
@Autowired
private IPvGatewayService gatewayService;
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 连接地址
*/
private String hostUrl;
/**
* 客户Id
*/
private String clientId;
/**
* 默认连接话题
*/
private String defaultTopic;
/**
* 超时时间
*/
private int timeout;
/**
* 保持连接数
*/
private int keepalive;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getHostUrl() {
return hostUrl;
}
public void setHostUrl(String hostUrl) {
this.hostUrl = hostUrl;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getDefaultTopic() {
return defaultTopic;
}
public void setDefaultTopic(String defaultTopic) {
this.defaultTopic = defaultTopic;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public int getKeepalive() {
return keepalive;
}
public void setKeepalive(int keepalive) {
this.keepalive = keepalive;
}
/**
* 连接至mqtt服务器,获取mqtt连接
*
* @return
*/
@Bean
public MqttPushClient getMqttPushClient() {
//连接至mqtt服务器,获取mqtt连接
mqttPushClient.connect(hostUrl, clientId, username, password, timeout, keepalive);
//一连接mqtt,就订阅默认需要订阅的主题(如test_queue)
// mqttSubClient.subScribeDataPublishTopic(defaultTopic);
List<String> gatewayTopicList = gatewayService.selectPvGatewaySubscribeList();//从数据库动态获取订阅主题
for (String topic : gatewayTopicList){
if (topic == null || topic.isEmpty()) {
// log.error("遇到空的订阅主题: '{}'", topic);
continue;
}
mqttSubClient.subscribe(topic);
}
return mqttPushClient;
}
}
2.发布连接类:
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* 发布连接类
* @author cls
* @date 2024-8-19 11:00:00
*/
@Slf4j
@Component
public class MqttPushClient {
@Autowired
private PushCallback pushCallback;
private static MqttClient client;
public static void setClient(MqttClient client) {
MqttPushClient.client = client;
}
public static MqttClient getClient() {
return client;
}
public void connect(String host, String clientID, String username, String password, int timeout, int keepalive) {
try {
if (client==null) {
client = new MqttClient(host, clientID, new MemoryPersistence());
}
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(true);
options.setUserName(username);
options.setPassword(password.toCharArray());
options.setConnectionTimeout(timeout);
options.setKeepAliveInterval(keepalive);
// automaticReconnect 为 true 表示断线自动重连,但仅仅只是重新连接,并不订阅主题;在 connectComplete 回调函数重新订阅
options.setAutomaticReconnect(true);
MqttPushClient.setClient(client);
try {
//设置回调类
client.setCallback(pushCallback);
//client.connect(options);
IMqttToken iMqttToken = client.connectWithResult(options);
boolean complete = iMqttToken.isComplete();
log.info("MQTT连接" + (complete ? "成功" : "失败"));
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 发布,默认qos为0,非持久化
*
* @param topic 主题名
* @param pushMessage 消息
*/
public void publish(String topic, String pushMessage) {
publish(0, false, topic, pushMessage);
}
/**
* 发布
*
* @param qos
* @param retained
* @param topic
* @param pushMessage
*/
public void publish(int qos, boolean retained, String topic, String pushMessage) {
MqttMessage message = new MqttMessage();
message.setQos(qos);
message.setRetained(retained);
message.setPayload(pushMessage.getBytes());
MqttTopic mTopic = MqttPushClient.getClient().getTopic(topic);
if (null == mTopic) {
log.error("主题不存在:{}", mTopic);
}
try {
mTopic.publish(message);
} catch (Exception e) {
log.error("mqtt发送消息异常:", e);
}
}
}
3.订阅类:
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.stereotype.Component;
/**
* 订阅类
* @author cls
* @date 2024-8-19 11:00:00
*/
@Slf4j
@Component
public class MqttSubClient {
public void subScribeDataPublishTopic(String defaultTopic) {
//订阅test_queue主题
String mqtt_topic[] = defaultTopic.split(",");
for (int i = 0; i < mqtt_topic.length; i++) {
subscribe(mqtt_topic[i], 0);//订阅主题
}
}
/**
* 订阅某个主题,qos默认为0
*
* @param topic
*/
public void subscribe(String topic) {
subscribe(topic, 0);
}
/**
* 订阅某个主题
*
* @param topic 主题名
* @param qos
*/
public void subscribe(String topic, int qos) {
try {
MqttClient client = MqttPushClient.getClient();
if (client == null) return;
client.subscribe(topic, qos);
log.info("订阅主题:{}", topic);
} catch (MqttException e) {
e.printStackTrace();
}
}
}
4.回调类:
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* 回调类
* @author cls
* @date 2024-8-19 11:00:00
*/
@Slf4j
@Component
public class PushCallback implements MqttCallback {
@Autowired
private MqttConfig mqttConfig;
@Override
public void connectionLost(Throwable cause) {
// 连接丢失后,一般在这里面进行重连
log.info("连接断开,正在重连");
mqttConfig.getMqttPushClient();
}
/**
* 发送消息,消息到达后处理方法
*
* @param token
*/
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
log.info("deliveryComplete---------" + token.isComplete());
}
/**
* 订阅主题接收到消息处理方法
*
* @param topic
* @param message
*/
@Override
public void messageArrived(String topic, MqttMessage message) {
// subscribe后得到的消息会执行到这里面,这里在控制台有输出
log.info("接收消息主题 : " + topic);
log.info("接收消息Qos : " + message.getQos());
log.info("接收消息内容 : " + new String(message.getPayload()));
}
}