work4-16/src/main/java/com/yao/common/mqtt/MqttConnectService.java

56 lines
1.7 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.yao.common.mqtt;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.yao.common.redis.service.RedisService;
import lombok.extern.log4j.Log4j2;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
/**
* @Author: LiJiaYao
* @Date: 2024/4/16
* @Description: 连接mqttx的配置类
*/
@Component
@Log4j2
public class MqttConnectService {
/**
* 调用redis分装好的方法
*/
@Autowired
private RedisService redisService;
//todo-----------------------连接mqtt方法-------------------
/**
* 连接mqtt方法
*/
public Integer connectMqtt(String ip) {
//请求路径
String URL = "http://" + ip + ":8080/public/cluster";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(URL).get().addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)").addHeader("Accesstoken", "").build();
redisService.setCacheSet("ECS", ip);
Response response = null;
try {
response = client.newCall(request).execute();
log.info(response);
JSONArray jsonArray = JSONArray.parseArray(response.body().string());
JSONObject object = jsonArray.getJSONObject(0);
JSONObject mqttInfo = object.getJSONObject("mqttInfo");
int connectSize = mqttInfo.getIntValue("connectSize");
log.info(ip + " 的fluxmq连接数为" + connectSize);
return connectSize;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}