判断mqtt客户端是否在线
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
package com.njcn.access.utils;
|
||||
|
||||
import com.alibaba.nacos.shaded.com.google.common.reflect.TypeToken;
|
||||
import com.alibaba.nacos.shaded.com.google.gson.Gson;
|
||||
import com.njcn.access.config.MqttInfo;
|
||||
import com.njcn.access.pojo.dto.mqtt.MqttClientDto;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import okhttp3.Credentials;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.annotation.Order;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* 类的介绍:
|
||||
*
|
||||
* @author xuyang
|
||||
* @version 1.0.0
|
||||
* @createTime 2023/7/14 14:44
|
||||
*/
|
||||
@Data
|
||||
@Order(100)
|
||||
@Configuration
|
||||
@AllArgsConstructor
|
||||
public class MqttUtil {
|
||||
|
||||
private final MqttInfo mqttInfo;
|
||||
|
||||
public boolean judgeClientOnline(String id) {
|
||||
boolean result = false;
|
||||
try {
|
||||
Gson gson = new Gson();
|
||||
OkHttpClient client = new OkHttpClient();
|
||||
Request request = new Request.Builder()
|
||||
.url(mqttInfo.getUrl() + "/api/v5/clients/" + id)
|
||||
.header("Content-Type", "application/json")
|
||||
.header("Authorization", Credentials.basic(mqttInfo.getUserName(), mqttInfo.getPassword()))
|
||||
.build();
|
||||
Response response = client.newCall(request).execute();
|
||||
response.body();
|
||||
MqttClientDto mqttClientDto = gson.fromJson(Objects.requireNonNull(response.body()).string(), new TypeToken<MqttClientDto>(){}.getType());
|
||||
result = mqttClientDto.isConnected();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user