刚使用thingsboard3.4的时候,不清楚thingsboard能够支持多了设备,如果项目中真的要用起来,不免要对它进行测试,花了不少时间写的,特此记录。
mqtt连接请参考:
https://blog.csdn.net/qq_40351360/article/details/127678653
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
package com.example.demo.http;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.mqtt.MqConfig;
import com.example.demo.mqtt.MqUtils;
import com.example.demo.mqtt.SubMessageListener;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;
import java.io.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* 1.第一次启动生成1000个设备,并生成文件记录
* 2.第二次可以连接100台设备并发送数据,可进行压测
* @date 2022/10/28 10:32
*/
public class Demo {
private static final Logger logger = LoggerFactory.getLogger(Demo.class);
private static String host = "192.122.11.151";
private static int port = 5530;
private static String deviceProfileId = "0bf257f0-5511-11ed-b43a-e174163c10d7";
private static String prefix = "aaa_";
private static String username = "abc1124";
private static String password = "abc1124";
private static String path = "d://record.log";
private static int threadNum = 0;
private static ThreadPoolExecutor sendData = new ThreadPoolExecutor(threadNum, 60, 60 * 3, TimeUnit.SECONDS, new LinkedBlockingQueue(10000), new CustomizableThreadFactory("testThreadPool"), new ThreadPoolExecutor.CallerRunsPolicy());
static {
threadNum = (int) Math.floor(Runtime.getRuntime().availableProcessors() / (1 - 0.8));
}
public static void main(String[] args) {
String hostUrl = host + ":" + port;
Boolean correct = false;
Boolean fileExists = true;
//将生成的设备id写入到文件中
File file = new File(path);
if (!file.exists()) {
try {
fileExists = false;
file.createNewFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Set<String> deviceClientIds = new HashSet<>();
//判断文件中是否存在1000个设备
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = null;
int i = 0;
while ((line = reader.readLine()) != null) {
i++;
//logger.info("{}=readLine data:{}", i, line);
if (line.length() < 37) {
continue;
}
String uuid = line.split(",")[1];
if (uuid.length() == 36 && uuid.contains("-")) {
deviceClientIds.add(uuid);
}
}
if (i == 1006) {
correct = true;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
if (correct) {
//开始发送数据
logger.info("开始发送数据...");
Map<String, MqttClient> map = new HashMap<>();
try {
//创建设备连接
int a1 = 1;
for (String uuid : deviceClientIds) {
/*if (!"2ceb25f4-af1a-4b02-8fa0-ab9223174b3e".equals(uuid)) {
continue;
}*/
MqttClient mqttClient = MqUtils.connect("tcp://192.168.1.51:5200", uuid, username, password);
if (mqttClient.isConnected()) {
System.out.println(uuid);
//
subMsg(mqttClient, "v1/devices/me/attributes", a1 + "");
subMsg(mqttClient, "v1/devices/me/attributes/response/+", a1 + "");
subMsg(mqttClient, "v1/devices/me/rpc/request/+", a1 + "");
subMsg(mqttClient, "v1/devices/me/rpc/response/+", a1 + "");
subMsg(mqttClient, "v2/fw/response/+/chunk/+", a1 + "");
/* ThreadDemo threadDemo = new ThreadDemo(mqttClient, a1, null, username, password);
threadDemo.publish("{\"current_fw_title\":\"Initial\",\n" +
" \"current_fw_version\":\"v0\"" +
" }", "v1/devices/me/telemetry");*/
/*threadDemo.publish("{\"current_fw_title\":\"Initial\",\n" +
" \"current_fw_version\":\"v0\",\n" +
" \"fw_state\":\"DOWNLOADING\"\n" +
" }", "v1/devices/me/telemetry");*/
//threadDemo.publish("{\"sharedKeys\": \"fw_version,fw_checksum_algorithm,fw_checksum,fw_size,fw_title,fw_version\"}", "v1/devices/me/attributes/request/1");
/*int i = (int) Math.ceil(421320 / 1320)+1;
for (int a = 1; a <= i; a++) {
System.out.println("a: "+a);
threadDemo.setI(a);
threadDemo.publish("1320", "v2/fw/request/" + a + "/chunk/" + (a-1));
}*/
map.put(uuid, mqttClient);
}
a1++;
}
logger.info("连接设备数:{}台", map.size());
logger.info("10秒后开始发送数据");
Thread.sleep(2000000);
while (true) {
long startTime = System.currentTimeMillis();
int active = 0;
for (Map.Entry<String, MqttClient> entry : map.entrySet()) {
if (entry.getValue().isConnected()) {
active++;
}
}
logger.info("存活数{}", active);
for (int i = 0; i < 1000; i++) {
int a = 1;
for (Map.Entry<String, MqttClient> entry : map.entrySet()) {
a++;
//发送数据
sendData.execute(new ThreadDemo(entry.getValue(), a, entry.getKey(), username, password));
}
}
logger.info("耗时:{}毫秒", (System.currentTimeMillis() - startTime));
Thread.sleep(60000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (fileExists) {
logger.info("结束...");
return;
}
createDevices(hostUrl, file);
logger.info("结束...");
}
private static void subMsg(MqttClient mqttClient, String topic, String id) throws MqttException {
if (mqttClient != null) {
int[] Qos = {MqConfig.qos};
String[] topics = {topic};
mqttClient.subscribe(topics, Qos);
}
mqttClient.subscribe(topic, MqConfig.qos, new SubMessageListener(id, mqttClient, topic));
}
private static void createDevices(String hostUrl, File file) {
//第一步获取token
JSONObject resultJson = Http.getLoginJsonObject(hostUrl);
if (resultJson == null) return;
String token = resultJson.getString("token");
BufferedWriter writer = null;
FileWriter fw = null;
try {
fw = new FileWriter(file);
writer = new BufferedWriter(fw);
writer.write(host + "\n");
writer.write(port + "\n");
writer.write(deviceProfileId + "\n");
writer.write(prefix + "\n");
writer.write(username + "\n");
writer.write(password + "\n");
} catch (Exception e) {
throw new RuntimeException(e);
}
for (int i = 0; i < 1000; i++) {
//第二步添加设备
JSONObject deviceJson = Http.createDeviceJsonObject(hostUrl, deviceProfileId, token, prefix);
if (deviceJson == null) return;
//第三步获取凭据
JSONObject getCredentialsJson = Http.getCredentials(hostUrl, token, deviceJson, deviceProfileId);
if (getCredentialsJson == null) return;
//第四步 更新凭据
JSONObject updateCredentialsJson = Http.updateCredentials(hostUrl, token, deviceJson, getCredentialsJson, username, password);
if (updateCredentialsJson == null) return;
try {
// 带有缓冲区,可提高性能
writer.write(deviceJson.getJSONObject("id").getString("id") + "," + updateCredentialsJson.getString("uuid")+"," + deviceJson.getString("name") + "\n");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
try {
writer.close();
fw.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
package com.example.demo.http;
import com.alibaba.fastjson.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.UUID;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Http {
private static final Logger logger = LoggerFactory.getLogger(Http.class);
/**
* 发送get请求,参数为json
*
* @param url
* @param param body内容,json格式
* @param token 令牌
* @return
* @throws Exception
*/
public static String sendJsonByGetReq(String url, String param, String token) throws Exception {
logger.debug("[请求]:url={} {} body={} token={}", url, "GET", param, token);
String body = "";
//创建httpclient对象
CloseableHttpClient client = HttpClients.createDefault();
HttpGetWithEntity httpGetWithEntity = new HttpGetWithEntity(url);
HttpEntity httpEntity = new StringEntity(param, ContentType.APPLICATION_JSON);
httpGetWithEntity.setEntity(httpEntity);
httpGetWithEntity.addHeader("Content-Type", "application/json");
httpGetWithEntity.addHeader("X-Authorization", "Bearer " + token);
//执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = client.execute(httpGetWithEntity);
//获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, "utf-8");
}
//释放链接
response.close();
return body;
}
/**
* 改delete请求不能携带body数据
*
* @param methodUrl
* @param token
* @return
*/
public static String httpURLDELETECase(String methodUrl, String token) {
logger.debug("[请求]:url={} {} body={} token={}", methodUrl, "DELETE", token);
HttpURLConnection connection = null;
BufferedReader reader = null;
String line = null;
try {
URL url = new URL(methodUrl);
connection = (HttpURLConnection) url.openConnection();// 根据URL生成HttpURLConnection
connection.setDoInput(true); // 设置是否从connection读入,默认情况下是true;
connection.setRequestMethod("DELETE");// 默认DELETE请求
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("X-Authorization", "Bearer " + token);
connection.connect();// 建立TCP连接
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));// 发送http请求
StringBuilder result = new StringBuilder();
// 循环读取流
while ((line = reader.readLine()) != null) {
result.append(line).append(System.getProperty("line.separator"));// "\n"
}
return result.toString();
} else {
reader = new BufferedReader(new InputStreamReader(connection.getErrorStream(), "UTF-8"));// 发送http请求
StringBuilder result = new StringBuilder();
// 循环读取流
while ((line = reader.readLine()) != null) {
result.append(line).append(System.getProperty("line.separator"));// "\n"
}
logger.error("[访问错误]:{} {} {}", connection.getResponseCode(), methodUrl, result.toString());
return null;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
connection.disconnect();
}
return null;
}
/**
* 改get请求不能携带body数据
*
* @param methodUrl
* @param body
* @param token
* @return
*/
public static String httpURLGETCase(String methodUrl, String body, String token) {
logger.debug("[请求]:url={} {} body={} token={}", methodUrl, "GET", body, token);
HttpURLConnection connection = null;
BufferedReader reader = null;
String line = null;
try {
URL url = new URL(methodUrl);
connection = (HttpURLConnection) url.openConnection();// 根据URL生成HttpURLConnection
connection.setDoInput(true); // 设置是否从connection读入,默认情况下是true;
connection.setRequestMethod("GET");// 默认GET请求
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("X-Authorization", "Bearer " + token);
connection.connect();// 建立TCP连接
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));// 发送http请求
StringBuilder result = new StringBuilder();
// 循环读取流
while ((line = reader.readLine()) != null) {
result.append(line).append(System.getProperty("line.separator"));// "\n"
}
return result.toString();
} else {
reader = new BufferedReader(new InputStreamReader(connection.getErrorStream(), "UTF-8"));// 发送http请求
StringBuilder result = new StringBuilder();
// 循环读取流
while ((line = reader.readLine()) != null) {
result.append(line).append(System.getProperty("line.separator"));// "\n"
}
logger.error("[访问错误]:{} {} {}", connection.getResponseCode(), methodUrl, result.toString());
return null;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
connection.disconnect();
}
return null;
}
private static String httpURLPOSTCase(String methodUrl, String body, String token) {
logger.debug("[请求]:url={} {} body={} token={}", methodUrl, "POST", body, token);
HttpURLConnection connection = null;
OutputStream dataout = null;
BufferedReader reader = null;
String line = null;
try {
URL url = new URL(methodUrl);
connection = (HttpURLConnection) url.openConnection();// 根据URL生成HttpURLConnection
connection.setDoOutput(true);// 设置是否向connection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true,默认情况下是false
connection.setDoInput(true); // 设置是否从connection读入,默认情况下是true;
connection.setRequestMethod("POST");// 设置请求方式为post,默认GET请求
connection.setUseCaches(false);// post请求不能使用缓存设为false
connection.setConnectTimeout(3000);// 连接主机的超时时间
connection.setReadTimeout(3000);// 从主机读取数据的超时时间
connection.setInstanceFollowRedirects(true);// 设置该HttpURLConnection实例是否自动执行重定向
connection.setRequestProperty("connection", "Keep-Alive");// 连接复用
connection.setRequestProperty("charset", "utf-8");
if (token != null && token != "") {
connection.setRequestProperty("X-Authorization", "Bearer " + token);
}
connection.setRequestProperty("Content-Type", "application/json");
connection.connect();// 建立TCP连接,getOutputStream会隐含的进行connect,所以此处可以不要
dataout = new DataOutputStream(connection.getOutputStream());// 创建输入输出流,用于往连接里面输出携带的参数
dataout.write(body.getBytes());
dataout.flush();
dataout.close();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));// 发送http请求
StringBuilder result = new StringBuilder();
// 循环读取流
while ((line = reader.readLine()) != null) {
result.append(line).append(System.getProperty("line.separator"));//
}
return result.toString();
} else {
reader = new BufferedReader(new InputStreamReader(connection.getErrorStream(), "UTF-8"));// 发送http请求
StringBuilder result = new StringBuilder();
// 循环读取流
while ((line = reader.readLine()) != null) {
result.append(line).append(System.getProperty("line.separator"));// "\n"
}
logger.error("[访问错误]:{} {} {}", connection.getResponseCode(), methodUrl, result.toString());
return null;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
connection.disconnect();
}
return null;
}
public static JSONObject updateCredentials(String hostUrl, String token, JSONObject deviceJson, JSONObject getCredentialsJson, String username, String password) {
String uuid = UUID.randomUUID().toString();
String body = "{\n" +
"\t\"id\": {\n" +
"\t\t\"id\": \"" + getCredentialsJson.getJSONObject("id").getString("id") + "\"\n" +
"\t},\n" +
"\t\"createdTime\": 1666667853734,\n" +
"\t\"deviceId\": {\n" +
"\t\t\"entityType\": \"DEVICE\",\n" +
"\t\t\"id\": \"" + deviceJson.getJSONObject("id").getString("id") + "\"\n" +
"\t},\n" +
"\t\"credentialsType\": \"MQTT_BASIC\",\n" +
"\t\"credentialsId\": null,\n" +
"\t\"credentialsValue\": \"{\\\"clientId\\\":\\\"" + uuid + "\\\",\\\"userName\\\":\\\"" + username + "\\\",\\\"password\\\":\\\"" + password + "\\\"}\"\n" +
"}\n";
String updateCredentials = httpURLPOSTCase("http://" + hostUrl + "/api/device/credentials", body, token);
logger.debug("[返回数据]:" + updateCredentials);
if (updateCredentials == null || updateCredentials == "") {
logger.error("失败!");
return null;
}
JSONObject credentialsJson = JSONObject.parseObject(updateCredentials);
if (!credentialsJson.containsKey("id")) {
logger.error("更新凭据失败!");
return null;
}
logger.info("更新凭据凭据成功!");
logger.debug("uuid={}",uuid);
credentialsJson.put("uuid", uuid);
return credentialsJson;
}
public static JSONObject getCredentials(String hostUrl, String token, JSONObject deviceJson, String deviceProfileId) {
String body = "{\n" +
" \"id\": {\n" +
" \"entityType\": \"DEVICE\",\n" +
" \"id\": \"" + deviceJson.getJSONObject("id").getString("id") + "\"\n" +
" },\n" +
" \"createdTime\": 1666669039384,\n" +
" \"additionalInfo\": {\n" +
" \"gateway\": false,\n" +
" \"overwriteActivityTime\": false,\n" +
" \"description\": \"\"\n" +
" },\n" +
" \"tenantId\": {\n" +
" \"entityType\": \"TENANT\",\n" +
" \"id\": \"" + deviceJson.getJSONObject("tenantId").getString("id") + "\"\n" +
" },\n" +
" \"customerId\": {\n" +
" \"entityType\": \"CUSTOMER\",\n" +
" \"id\": \"" + deviceJson.getJSONObject("customerId").getString("id") + "\"\n" +
" },\n" +
" \"name\": \"" + deviceJson.getString("name") + "\",\n" +
" \"type\": \"" + deviceJson.getString("type") + "\",\n" +
" \"label\": \"" + deviceJson.getString("label") + "\",\n" +
" \"deviceProfileId\": {\n" +
" \"entityType\": \"DEVICE_PROFILE\",\n" +
" \"id\": \"" + deviceProfileId + "\"\n" +
" },\n" +
" \"deviceData\": {\n" +
" \"configuration\": {\n" +
" \"type\": \"DEFAULT\"\n" +
" },\n" +
" \"transportConfiguration\": {\n" +
" \"type\": \"DEFAULT\"\n" +
" }\n" +
" },\n" +
" \"firmwareId\": null,\n" +
" \"softwareId\": null,\n" +
" \"externalId\": null,\n" +
" \"customerTitle\": null,\n" +
" \"customerIsPublic\": false,\n" +
" \"deviceProfileName\": \"default\"\n" +
"}";
String deviceId = deviceJson.getJSONObject("id").getString("id");
String credentials = null;
try {
credentials = sendJsonByGetReq("http://" + hostUrl + "/api/device/" + deviceId + "/credentials", body, token);
} catch (Exception e) {
throw new RuntimeException(e);
}
logger.debug("[返回数据]:" + credentials);
if (credentials == null || credentials == "") {
logger.error("失败!");
return null;
}
JSONObject credentialsJson = JSONObject.parseObject(credentials);
if (!credentialsJson.containsKey("id")) {
logger.error("获取凭据失败!");
return null;
}
logger.info("获取凭据成功!");
return credentialsJson;
}
public static JSONObject getLoginJsonObject(String hostUrl) {
JSONObject jsonObject = new JSONObject(true);
jsonObject.put("username", "[email protected]");
jsonObject.put("password", "123456");
String result = httpURLPOSTCase("http://" + hostUrl + "/api/auth/login", jsonObject.toJSONString(), null);
logger.debug("[返回数据]:" + result);
if (result == null || result == "") {
logger.error("失败!");
return null;
}
JSONObject resultJson = JSONObject.parseObject(result);
if (!resultJson.containsKey("token")) {
logger.error("登录失败!");
return null;
}
logger.info("登录成功!");
return resultJson;
}
public static JSONObject createDeviceJsonObject(String hostUrl, String deviceProfileId, String token, String prefix) {
String body = "{\n" +
"\t\"name\": \"" + prefix + System.currentTimeMillis() + "\",\n" +
"\t \"type\": \"interface\",\n" +
"\t\"label\": \"interface\",\n" +
"\t\"deviceProfileId\": {\n" +
"\t\t\"entityType\": \"DEVICE_PROFILE\",\n" +
"\t\t\"id\": \"" + deviceProfileId + "\"\n" +
"\t},\n" +
"\t\"additionalInfo\": {\n" +
"\t\t\"gateway\": false,\n" +
"\t\t\"overwriteActivityTime\": false,\n" +
"\t\t\"description\": \"\"\n" +
"\t},\n" +
"\t\"customerId\": null\n" +
"}";
String resultDevice = httpURLPOSTCase("http://" + hostUrl + "/api/device", body, token);
logger.debug("[返回数据]:" + resultDevice);
if (resultDevice == null || resultDevice == "") {
logger.error("失败!");
return null;
}
JSONObject resultDeviceJson = JSONObject.parseObject(resultDevice);
if (!resultDeviceJson.containsKey("id")) {
logger.error("创建设备失败!");
return null;
}
logger.info("创建设备成功!");
return resultDeviceJson;
}
}
package com.example.demo.http;
import com.alibaba.fastjson.JSONObject;
import java.io.*;
/**
* @author Xiaoxiangdong
* @date 2022/10/28 15:25
*/
public class DeleteDemo {
private static String host = "192.168.1.51";
private static int port = 5300;
private static String path = "d://record.log";
private static String deviceProfileId = "0bf257f0-5511-11ed-b43a-e174163c10d7";
private static String prefix = "xxd_";
private static String username = "abc1124";
private static String password = "abc1124";
public static void main(String[] args) {
File file = new File(path);
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
String hostUrl = host + ":" + port;
//第一步获取token
JSONObject resultJson = Http.getLoginJsonObject(hostUrl);
if (resultJson == null) return;
String token = resultJson.getString("token");
String line = null;
int i = 0;
while (true) {
try {
if (!((line = reader.readLine()) != null)) break;
} catch (IOException e) {
throw new RuntimeException(e);
}
i++;
if (line.length() < 37) {
continue;
}
String id = line.split(",")[0];
Http.httpURLDELETECase("http://" + hostUrl + "/api/device/"+id,token);
}
}
}
package com.example.demo.http;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.mqtt.MqConfig;
import com.example.demo.mqtt.MqUtils;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.UUID;
public class ThreadDemo implements Runnable {
private MqttClient mqttClient;
private int i;
private String uuid;
private String username;
private String password;
public void setI(int i) {
this.i = i;
}
private static final Logger logger = LoggerFactory.getLogger(ThreadDemo.class);
public ThreadDemo(MqttClient mqttClient, int i, String uuid, String username, String password) {
this.mqttClient = mqttClient;
this.i = i;
this.uuid = uuid;
this.username = username;
this.password = password;
}
@Override
public void run() {
try {
JSONObject jsonObject=new JSONObject();
jsonObject.put("record","aaaaaa" + UUID.randomUUID() + "bbbbbbbbbbbbbbbbbb");
publish(jsonObject.toJSONString(), "v1/devices/me/telemetry");
} catch (MqttException e) {
throw new RuntimeException(e);
}
}
public void publish(String msg, String topic) throws MqttException {
if (mqttClient != null) {
if (mqttClient.isConnected()) {
logger.info("发送消息-{}:{}", i, msg);
MqttMessage message = new MqttMessage(msg.getBytes());
message.setQos(MqConfig.qos);
//重新连接MQTT服务时,不需要接收该主题最新消息,设置retained为false
//重新连接MQTT服务时,需要接收该主题最新消息,设置retained为true;
message.setRetained(true);
mqttClient.publish(topic, message);
} else {
logger.error("设备{}断开连接", i);
}
}
}
}
package com.example.demo.http;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import java.net.URI;
/**
* 定义一个带body的GET请求 继承 HttpEntityEnclosingRequestBase
* @date 2022/10/28 10:19
*/
public class HttpGetWithEntity extends HttpEntityEnclosingRequestBase {
private final static String METHOD_NAME = "GET";
@Override
public String getMethod() {
return METHOD_NAME;
}
public HttpGetWithEntity() {
super();
}
public HttpGetWithEntity(final URI uri) {
super();
setURI(uri);
}
HttpGetWithEntity(final String uri) {
super();
setURI(URI.create(uri));
}
}