判断mqtt客户端是否在线

This commit is contained in:
2023-07-17 16:27:28 +08:00
parent 153a9ae1a5
commit 3fc99d6d68
6 changed files with 119 additions and 5 deletions

View File

@@ -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;
}
}