You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
85 lines
2.1 KiB
85 lines
2.1 KiB
2 years ago
|
package com.psdc.mqtt;
|
||
|
|
||
|
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.Value;
|
||
|
import org.springframework.context.annotation.Bean;
|
||
|
import org.springframework.context.annotation.Configuration;
|
||
|
|
||
|
/**
|
||
|
* mqtt配置类
|
||
|
*/
|
||
|
@Configuration
|
||
|
@Slf4j
|
||
|
public class MqttProviderConfig {
|
||
|
|
||
|
@Value("${mqtt.url}")
|
||
|
private String url;
|
||
|
|
||
|
@Value("${mqtt.username}")
|
||
|
private String username;
|
||
|
|
||
|
@Value("${mqtt.password}")
|
||
|
private String password;
|
||
|
|
||
|
@Value("${mqtt.qos}")
|
||
|
private String qos;
|
||
|
|
||
|
@Value("${mqtt.clientId}")
|
||
|
private String clientId;
|
||
|
|
||
|
@Value("${mqtt.timeOut}")
|
||
|
private int timeOut;
|
||
|
|
||
|
@Value("${mqtt.keepAlive}")
|
||
|
private int keepAlive;
|
||
|
|
||
2 years ago
|
@Value("${mqtt.dataTopic}")
|
||
|
private String dataTopic;
|
||
2 years ago
|
|
||
2 years ago
|
@Value("${mqtt.controlTopic}")
|
||
|
private String controlTopic;
|
||
2 years ago
|
|
||
2 years ago
|
@Value("${mqtt.controlResponseTopic}")
|
||
|
private String controlResponseTopic;
|
||
2 years ago
|
|
||
|
/**
|
||
|
* 客户端对象
|
||
|
*/
|
||
|
private MqttClient client;
|
||
|
|
||
|
/**
|
||
|
* 客户端连接服务端
|
||
|
*
|
||
|
* @param
|
||
|
* @return void
|
||
|
* @date 2021/7/30 16:01
|
||
|
*/
|
||
|
|
||
|
@Bean
|
||
|
public MyMQTTClient connect() {
|
||
|
//创建MQTT客户端对象
|
||
|
MyMQTTClient myMQTTClient = new MyMQTTClient(url, username, password, clientId, timeOut, keepAlive);
|
||
|
for (int i = 0; i < 10; i++) {
|
||
|
try {
|
||
|
myMQTTClient.connect();
|
||
|
//不同的主题
|
||
2 years ago
|
myMQTTClient.subscribe(dataTopic, 0);
|
||
2 years ago
|
myMQTTClient.subscribe(controlTopic, 0);
|
||
|
myMQTTClient.subscribe(controlResponseTopic, 0);
|
||
2 years ago
|
return myMQTTClient;
|
||
|
} catch (MqttException e) {
|
||
|
log.error("MQTT connect exception,connect time = " + i);
|
||
|
try {
|
||
|
Thread.sleep(2000);
|
||
|
} catch (InterruptedException e1) {
|
||
|
e1.printStackTrace();
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
return myMQTTClient;
|
||
|
}
|
||
|
|
||
|
}
|