springboot整合多个mqtt
前提:实际应用中,项目需要订阅其他服务器的消息,并且把本机消息发布,所以需要连接多个mqtt,实现不同的需求
参考:https://blog.csdn.net/qq_40083897/article/details/117333716
整合大致结构如下:
1. 引入依赖
<!-- mqtt -->
<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.连接配置
#MQTT配置信息
mqtt:
# 设备连接
channel1:
username: xxxxxx
password: xxxxxx
host: tcp://192.168.xx.xxx:1883
clientid: device_channel1
timeout: 1000
keepalive: 10
cleanSession: false
#本地连接
channel2:
username: xxxxxx
password: xxxxxx
host: tcp://192.168.xx.xxx:1883
clientid: local_channel2
timeout: 1000
keepalive: 10
cleanSession: false
3.连接配置
@Data
public class MqttConfiguration {
private String host;
private String clientId;
private String userName;
private String password;
private String topic;
private int timeout;
private int keepAlive;
private boolean cleanSession;
}
@Slf4j
@Component
@Configuration
@ConfigurationProperties(MqttConfiguration1.PREFIX)
public class MqttConfiguration1 extends MqttConfiguration{
//指定配置文件application-local.properties中的属性名前缀
public static final String PREFIX = "spring.mqtt.channel1";
}
@Slf4j
@Component
@Configuration
@ConfigurationProperties(MqttConfiguration2.PREFIX)
public class MqttConfiguration2 extends MqttConfiguration{
//指定配置文件application-local.properties中的属性名前缀
public static final String PREFIX = "spring.mqtt.channel2";
}
4.连接管理
@Slf4j
@Component
public class MqttClientConnection {
private MqttClient mqttClient;
/**
* 系统的mqtt客户端id
*/
private String mqttClientId;
/**
* 客户端
*/
public static ConcurrentHashMap<String, MqttClientConnection> mqttClients = new ConcurrentHashMap();
/**
* 客户端connect连接mqtt服务器
*
* @param userName 用户名
* @param passWord 密码
* @param mqttCallback 回调函数
**/
public MqttClient setMqttClient(String host, String clientId, String userName, String passWord, boolean cleanSession, MqttCallback mqttCallback) throws MqttException {
MqttConnectOptions options = mqttConnectOptions(host, clientId, userName, passWord, cleanSession);
if (mqttCallback == null) {
mqttClient.setCallback(new MqttClientCallback(mqttClientId));
} else {
mqttClient.setCallback(mqttCallback