Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0d4db672e1 | |||
| 37ffaa3ad4 | |||
| c4db053243 | |||
| 0fda2354eb | |||
| 1a3e443be1 | |||
| f88baa52be | |||
| 72351c612b |
@@ -1,15 +1,8 @@
|
||||
package com.njcn.access.api;
|
||||
|
||||
import com.njcn.access.api.fallback.AskDeviceDataClientFallbackFactory;
|
||||
import com.njcn.common.pojo.annotation.OperateInfo;
|
||||
import com.njcn.common.pojo.constant.ServerInfo;
|
||||
import com.njcn.common.pojo.enums.common.LogEnum;
|
||||
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
|
||||
import com.njcn.common.pojo.response.HttpResult;
|
||||
import com.njcn.common.utils.HttpResultUtil;
|
||||
import io.swagger.annotations.ApiImplicitParam;
|
||||
import io.swagger.annotations.ApiImplicitParams;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
@@ -41,4 +34,7 @@ public interface AskDeviceDataFeignClient {
|
||||
@PostMapping("/askRealData")
|
||||
HttpResult<String> askRealData(@RequestParam("nDid") String nDid, @RequestParam("idx") Integer idx, @RequestParam("clDId") Integer clDId);
|
||||
|
||||
@PostMapping("/askCldRealData")
|
||||
HttpResult<String> askCldRealData(@RequestParam("devId") String devId, @RequestParam("lineId") String lineId, @RequestParam("nodeId") String nodeId, @RequestParam("idx") Integer idx);
|
||||
|
||||
}
|
||||
|
||||
@@ -73,6 +73,12 @@ public class AskDeviceDataClientFallbackFactory implements FallbackFactory<AskDe
|
||||
log.error("{}异常,降级处理,异常为:{}","询问装置实时数据",cause.toString());
|
||||
throw new BusinessException(finalExceptionEnum);
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpResult<String> askCldRealData(String devId, String lineId, String nodeId, Integer idx) {
|
||||
log.error("{}异常,降级处理,异常为:{}","询问云前置实时数据",cause.toString());
|
||||
throw new BusinessException(finalExceptionEnum);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,7 +56,7 @@ public enum AccessResponseEnum {
|
||||
CTRL_DICT_MISSING("A0307","Ctrl字典数据缺失!"),
|
||||
WAVE_INFO_MISSING("A0307","波形参数缺失!"),
|
||||
|
||||
MODEL_MISS("A0308","模板信息缺失!"),
|
||||
MODEL_MISS("A0308","询问模板信息超时,设备未响应!"),
|
||||
MODEL_VERSION_ERROR("A0308","询问装置模板信息错误"),
|
||||
UPLOAD_ERROR("A0308","平台上送文件异常"),
|
||||
RELOAD_UPLOAD_ERROR("A0308","平台重新上送文件异常"),
|
||||
@@ -73,6 +73,8 @@ public enum AccessResponseEnum {
|
||||
PROCESS_ERROR("A0311","调试流程异常,请先进行功能调试、出厂调试!"),
|
||||
|
||||
FILE_CHECK_ERROR("A0312","文件校验码不一致!"),
|
||||
|
||||
CLD_MODEL_EXIST("A0313","云前置模板已存在,请先删除再录入!"),
|
||||
;
|
||||
|
||||
private final String code;
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.njcn.access.utils;
|
||||
|
||||
import com.njcn.redis.utils.RedisUtil;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* @author 徐扬
|
||||
*/
|
||||
@Component
|
||||
@Slf4j
|
||||
public class RedisSetUtil {
|
||||
|
||||
@Autowired
|
||||
private RedisUtil redisUtil;
|
||||
|
||||
/**
|
||||
* 向Redis Set中添加元素
|
||||
*/
|
||||
public void addToSet(String key, String value, long expireSeconds) {
|
||||
try {
|
||||
Object existing = redisUtil.getObjectByKey(key);
|
||||
Set<String> set = convertToSet(existing);
|
||||
set.add(value);
|
||||
redisUtil.saveByKeyWithExpire(key, set, expireSeconds);
|
||||
} catch (Exception e) {
|
||||
log.error("向Redis Set添加元素失败,key: {}", key, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从Redis Set中移除元素
|
||||
*/
|
||||
public void removeFromSet(String key, String value) {
|
||||
try {
|
||||
Object existing = redisUtil.getObjectByKey(key);
|
||||
if (existing != null) {
|
||||
Set<String> set = convertToSet(existing);
|
||||
set.remove(value);
|
||||
redisUtil.saveByKey(key, set);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("从Redis Set移除元素失败,key: {}", key, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全的对象到Set转换
|
||||
*/
|
||||
public Set<String> convertToSet(Object obj) {
|
||||
if (obj == null) {
|
||||
return new HashSet<>();
|
||||
}
|
||||
if (obj instanceof Set) {
|
||||
return new HashSet<>((Set<String>) obj);
|
||||
}
|
||||
if (obj instanceof Collection) {
|
||||
return new HashSet<>((Collection<String>) obj);
|
||||
}
|
||||
log.warn("无法转换的对象类型: {}", obj.getClass().getName());
|
||||
return new HashSet<>();
|
||||
}
|
||||
}
|
||||
@@ -123,5 +123,19 @@ public class AskDeviceDataController extends BaseController {
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||
}
|
||||
|
||||
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
|
||||
@PostMapping("/askCldRealData")
|
||||
@ApiOperation("询问云前置实时数据")
|
||||
@ApiImplicitParams({
|
||||
@ApiImplicitParam(name = "devId", value = "装置id"),
|
||||
@ApiImplicitParam(name = "lineId", value = "监测点id"),
|
||||
@ApiImplicitParam(name = "nodeId", value = "前置id"),
|
||||
@ApiImplicitParam(name = "idx", value = "数据集编号")
|
||||
})
|
||||
public HttpResult<String> askCldRealData(@RequestParam("devId") String devId, @RequestParam("lineId") String lineId, @RequestParam("nodeId") String nodeId, @RequestParam("idx") Integer idx){
|
||||
String methodDescribe = getMethodDescribe("askCldRealData");
|
||||
askDeviceDataService.askCldRealData(devId,lineId,nodeId,idx);
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -168,7 +168,7 @@ public class MqttMessageHandler {
|
||||
@MqttSubscribe(value = "/Dev/DevReg/{edgeId}",qos = 1)
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void devOperation(String topic, MqttMessage message, @NamedValue("edgeId") String nDid, @Payload String payload){
|
||||
log.info("收到注册应答响应--->" + nDid);
|
||||
log.info("收到注册应答响应--->{}", nDid);
|
||||
//日志记录
|
||||
DeviceLogDTO logDto = new DeviceLogDTO();
|
||||
try{
|
||||
@@ -458,7 +458,6 @@ public class MqttMessageHandler {
|
||||
default:
|
||||
break;
|
||||
}
|
||||
//csLogsFeignClient.addUserLog(logDto);
|
||||
} else {
|
||||
String result = getEnum(res.getCode());
|
||||
log.info(result);
|
||||
@@ -526,14 +525,14 @@ public class MqttMessageHandler {
|
||||
response.setPri(AccessEnum.FIRST_CHANNEL.getCode());
|
||||
response.setType(Integer.parseInt(TypeEnum.TYPE_15.getCode()));
|
||||
response.setCode(200);
|
||||
log.info("应答事件:" + new Gson().toJson(response));
|
||||
log.info("应答事件:{}", new Gson().toJson(response));
|
||||
publisher.send("/Dev/DataRsp/"+version+"/"+nDid,new Gson().toJson(response),1,false);
|
||||
}
|
||||
//判断事件类型
|
||||
switch (dataDto.getMsg().getDataAttr()) {
|
||||
//暂态事件、录波处理、工程信息
|
||||
case 0:
|
||||
log.info(nDid + "处理事件");
|
||||
log.info("{}处理事件", nDid);
|
||||
//log.info(nDid + "事件报文为:" + new String(message.getPayload(), StandardCharsets.UTF_8));
|
||||
EventDto eventDto = gson.fromJson(new String(message.getPayload(), StandardCharsets.UTF_8), EventDto.class);
|
||||
JSONObject jsonObject0 = JSONObject.parseObject(JSON.toJSONString(eventDto));
|
||||
@@ -543,7 +542,7 @@ public class MqttMessageHandler {
|
||||
break;
|
||||
//实时数据
|
||||
case 1:
|
||||
log.info(nDid + "处理实时数据");
|
||||
log.info("{}处理实时数据", nDid);
|
||||
JSONObject jsonObject2 = JSONObject.parseObject(JSON.toJSONString(dataDto));
|
||||
AppAutoDataMessage appAutoDataMessage = JSONObject.toJavaObject(jsonObject2, AppAutoDataMessage.class);
|
||||
appAutoDataMessage.setId(nDid);
|
||||
@@ -555,7 +554,7 @@ public class MqttMessageHandler {
|
||||
AppAutoDataMessage appAutoDataMessage2 = JSONObject.toJavaObject(jsonObject3, AppAutoDataMessage.class);
|
||||
appAutoDataMessage2.setId(nDid);
|
||||
appAutoDataMessage2.getMsg().getDataArray().forEach(item->{
|
||||
log.info(nDid + "处理统计数据" + item.getDataAttr());
|
||||
log.info("{}处理统计数据{}", nDid, item.getDataAttr());
|
||||
});
|
||||
appAutoDataMessageTemplate.sendMember(appAutoDataMessage2);
|
||||
break;
|
||||
@@ -588,7 +587,7 @@ public class MqttMessageHandler {
|
||||
//响应请求
|
||||
switch (fileDto.getType()){
|
||||
case 4657:
|
||||
log.info("获取文件信息" + fileDto);
|
||||
log.info("获取文件信息{}", fileDto);
|
||||
if (Objects.equals(fileDto.getCode(),AccessEnum.SUCCESS.getCode())) {
|
||||
String key = AppRedisKey.PROJECT_INFO + nDid;
|
||||
if (Objects.isNull(fileDto.getMsg().getType())) {
|
||||
@@ -669,7 +668,6 @@ public class MqttMessageHandler {
|
||||
public void devErrorInfo(String topic, MqttMessage message, @NamedValue("version") String version, @NamedValue("edgeId") String nDid, @Payload String payload) {
|
||||
//解析数据
|
||||
Gson gson = new Gson();
|
||||
//log.info(nDid + "事件报文为:" + new String(message.getPayload(), StandardCharsets.UTF_8));
|
||||
EventDto eventDto = gson.fromJson(new String(message.getPayload(), StandardCharsets.UTF_8), EventDto.class);
|
||||
JSONObject jsonObject0 = JSONObject.parseObject(JSON.toJSONString(eventDto));
|
||||
AppEventMessage appEventMessage = JSONObject.toJavaObject(jsonObject0, AppEventMessage.class);
|
||||
@@ -742,7 +740,6 @@ public class MqttMessageHandler {
|
||||
break;
|
||||
}
|
||||
reqAndResParam.setMsg(askDataDto);
|
||||
//log.info("askDevData的请求报文:" + new Gson().toJson(reqAndResParam));
|
||||
publisher.send("/Pfm/DevCmd/"+version+"/"+nDid, new Gson().toJson(reqAndResParam),1,false);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
package com.njcn.access.listener;
|
||||
|
||||
import cn.hutool.core.date.DatePattern;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.alibaba.nacos.shaded.com.google.gson.Gson;
|
||||
import com.github.tocrhz.mqtt.publisher.MqttPublisher;
|
||||
import com.njcn.access.enums.AccessEnum;
|
||||
import com.njcn.access.pojo.dto.NoticeUserDto;
|
||||
import com.njcn.access.pojo.po.CsDeviceOnlineLogs;
|
||||
import com.njcn.access.service.ICsDeviceOnlineLogsService;
|
||||
import com.njcn.access.service.ICsEquipmentDeliveryService;
|
||||
import com.njcn.access.service.ICsTopicService;
|
||||
import com.njcn.access.service.impl.CsDeviceServiceImpl;
|
||||
import com.njcn.access.utils.MqttUtil;
|
||||
import com.njcn.access.utils.RedisSetUtil;
|
||||
import com.njcn.access.utils.SendMessageUtil;
|
||||
import com.njcn.common.pojo.dto.DeviceLogDTO;
|
||||
import com.njcn.csdevice.api.*;
|
||||
@@ -17,6 +20,7 @@ import com.njcn.csdevice.pojo.dto.PqsCommunicateDto;
|
||||
import com.njcn.csdevice.pojo.po.CsEquipmentDeliveryPO;
|
||||
import com.njcn.redis.pojo.enums.AppRedisKey;
|
||||
import com.njcn.redis.utils.RedisUtil;
|
||||
import com.njcn.rt.pojo.dto.BaseRealDataSet;
|
||||
import com.njcn.user.api.AppUserFeignClient;
|
||||
import com.njcn.user.api.UserFeignClient;
|
||||
import com.njcn.user.pojo.po.User;
|
||||
@@ -32,6 +36,7 @@ import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
@@ -46,8 +51,6 @@ import java.util.stream.Collectors;
|
||||
@Component
|
||||
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
|
||||
|
||||
@Resource
|
||||
private ICsTopicService csTopicService;
|
||||
@Resource
|
||||
private ICsEquipmentDeliveryService csEquipmentDeliveryService;
|
||||
@Resource
|
||||
@@ -73,9 +76,11 @@ public class RedisKeyExpirationListener extends KeyExpirationEventMessageListene
|
||||
@Resource
|
||||
private SendMessageUtil sendMessageUtil;
|
||||
@Resource
|
||||
private CsDeviceServiceImpl csDeviceServiceImpl;
|
||||
@Resource
|
||||
private CsCommunicateFeignClient csCommunicateFeignClient;
|
||||
@Resource
|
||||
private MqttPublisher publisher;
|
||||
@Resource
|
||||
private RedisSetUtil redisSetUtil;
|
||||
|
||||
private final Object lock = new Object();
|
||||
|
||||
@@ -101,6 +106,27 @@ public class RedisKeyExpirationListener extends KeyExpirationEventMessageListene
|
||||
String nDid = expiredKey.split(":")[1];
|
||||
executeMainTask(nDid);
|
||||
}
|
||||
if(expiredKey.startsWith("cldRtDataOverTime:")){
|
||||
String lineId = expiredKey.split(":")[1];
|
||||
Object redisObject = redisUtil.getObjectByKey("rtDataUserId:"+lineId);
|
||||
if (ObjectUtil.isNotNull(redisObject)) {
|
||||
Set<String> userSet = redisSetUtil.convertToSet(redisObject);
|
||||
userSet.forEach(userId->{
|
||||
BaseRealDataSet baseRealDataSet = new BaseRealDataSet();
|
||||
baseRealDataSet.setUserId(userId);
|
||||
baseRealDataSet.setResult(false);
|
||||
baseRealDataSet.setContent("设备未响应,超时中断");
|
||||
publisher.send("/Web/RealData/" + lineId, new Gson().toJson(baseRealDataSet), 1, false);
|
||||
});
|
||||
}
|
||||
}
|
||||
//云前置设备心跳丢失处理
|
||||
// if(expiredKey.startsWith(RedisKeyEnum.CLD_HEART_BEAT_KEY.getKey())){
|
||||
// String node = expiredKey.split(":")[1];
|
||||
// String nodeId = node.substring(0, node.length() - 1);
|
||||
// int processNo = Integer.parseInt(node.substring(node.length() - 1));
|
||||
// equipmentFeignClient.updateCldDevStatus(nodeId,processNo);
|
||||
// }
|
||||
}
|
||||
|
||||
//主任务
|
||||
@@ -118,10 +144,6 @@ public class RedisKeyExpirationListener extends KeyExpirationEventMessageListene
|
||||
logDto.setOperate(nDid +"装置离线");
|
||||
sendMessage(nDid);
|
||||
//记录装置掉线时间
|
||||
// CsDeviceOnlineLogs record = onlineLogsService.findLastData(nDid);
|
||||
// record.setOfflineTime(LocalDateTime.now());
|
||||
// onlineLogsService.updateById(record);
|
||||
//记录装置掉线时间
|
||||
PqsCommunicateDto dto = new PqsCommunicateDto();
|
||||
dto.setTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
|
||||
dto.setDevId(nDid);
|
||||
@@ -131,68 +153,6 @@ public class RedisKeyExpirationListener extends KeyExpirationEventMessageListene
|
||||
csLogsFeignClient.addUserLog(logDto);
|
||||
}
|
||||
|
||||
//主任务
|
||||
//1.装置心跳断连
|
||||
//2.MQTT客户端不在线
|
||||
// private void executeMainTask(String nDid, String version) {
|
||||
// ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
|
||||
// log.info("{}->装置离线", nDid);
|
||||
// DeviceLogDTO logDto = new DeviceLogDTO();
|
||||
// logDto.setUserName("运维管理员");
|
||||
// logDto.setLoginName("njcnyw");
|
||||
// //判断mqtt
|
||||
// String clientName = "NJCN-" + nDid.substring(nDid.length() - 6);
|
||||
// boolean mqttClient = mqttUtil.judgeClientOnline(clientName);
|
||||
// //心跳异常,但是客户端在线,则发送接入请求
|
||||
// if (mqttClient) {
|
||||
// csDeviceService.devAccessAskTemplate(nDid,version,1);
|
||||
// redisUtil.saveByKey(AppRedisKey.DEVICE_MID + nDid,1);
|
||||
// try {
|
||||
// Thread.sleep(5000);
|
||||
// Object object = redisUtil.getObjectByKey("online" + nDid);
|
||||
// if (Objects.nonNull(object)) {
|
||||
// scheduler.shutdown();
|
||||
// logDto.setOperate(nDid + "客户端在线重连成功");
|
||||
// } else {
|
||||
// //装置下线
|
||||
// csEquipmentDeliveryService.updateRunStatusBynDid(nDid, AccessEnum.OFFLINE.getCode());
|
||||
// //装置调整为注册状态
|
||||
// csEquipmentDeliveryService.updateStatusBynDid(nDid,AccessEnum.REGISTERED.getCode());
|
||||
// logDto.setOperate(nDid +"装置离线");
|
||||
// sendMessage(nDid);
|
||||
//
|
||||
// //记录装置掉线时间
|
||||
// CsDeviceOnlineLogs record = onlineLogsService.findLastData(nDid);
|
||||
// record.setOfflineTime(LocalDateTime.now());
|
||||
// onlineLogsService.updateById(record);
|
||||
//
|
||||
// scheduler.shutdown();
|
||||
// }
|
||||
// } catch (InterruptedException e) {
|
||||
// scheduler.shutdown();
|
||||
// throw new RuntimeException(e);
|
||||
// }
|
||||
// csLogsFeignClient.addUserLog(logDto);
|
||||
// }
|
||||
// //客户端不在线则修改装置状态,进入定时任务
|
||||
// else {
|
||||
// //装置下线
|
||||
// csEquipmentDeliveryService.updateRunStatusBynDid(nDid, AccessEnum.OFFLINE.getCode());
|
||||
// //装置调整为注册状态
|
||||
// csEquipmentDeliveryService.updateStatusBynDid(nDid,AccessEnum.REGISTERED.getCode());
|
||||
// logDto.setOperate(nDid +"主任务执行失败,装置下线");
|
||||
// csLogsFeignClient.addUserLog(logDto);
|
||||
// sendMessage(nDid);
|
||||
//
|
||||
// //记录装置掉线时间
|
||||
// CsDeviceOnlineLogs record = onlineLogsService.findLastData(nDid);
|
||||
// record.setOfflineTime(LocalDateTime.now());
|
||||
// onlineLogsService.updateById(record);
|
||||
//
|
||||
// scheduler.shutdown();
|
||||
// }
|
||||
// }
|
||||
|
||||
private void startScheduledTask(ScheduledExecutorService scheduler, String nDid, String version) {
|
||||
synchronized (lock) {
|
||||
//判断是否推送消息
|
||||
|
||||
@@ -38,77 +38,197 @@ public class AutoAccessTimer implements ApplicationRunner {
|
||||
|
||||
@Override
|
||||
public void run(ApplicationArguments args) {
|
||||
if (scheduler.isShutdown() || scheduler.isTerminated()) {
|
||||
scheduler = Executors.newScheduledThreadPool(1);
|
||||
}
|
||||
Runnable task = () -> {
|
||||
log.info("轮询定时任务执行中!");
|
||||
List<CsEquipmentDeliveryPO> list = csEquipmentDeliveryService.getOfflineDev();
|
||||
if (CollUtil.isNotEmpty(list)) {
|
||||
ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||
// 将任务平均分配给10个子列表
|
||||
try {
|
||||
executeScheduledTask();
|
||||
}
|
||||
// 捕获所有Throwable,包括Error
|
||||
catch (Throwable t) {
|
||||
log.error("定时任务发生严重异常,尝试恢复", t);
|
||||
// 可以添加重启逻辑或告警
|
||||
}
|
||||
};
|
||||
ScheduledFuture<?> future = scheduler.scheduleWithFixedDelay(task, AUTO_TIME, AUTO_TIME, TimeUnit.SECONDS);
|
||||
// 添加监控,如果任务被取消则重新调度
|
||||
monitorScheduledTask(future);
|
||||
}
|
||||
|
||||
//10分钟检查一下调度任务
|
||||
private void monitorScheduledTask(ScheduledFuture<?> future) {
|
||||
Thread monitorThread = new Thread(() -> {
|
||||
while (!Thread.currentThread().isInterrupted()) {
|
||||
try {
|
||||
//每10分钟检查一次
|
||||
Thread.sleep(600000);
|
||||
if (future.isCancelled() || future.isDone()) {
|
||||
log.warn("定时任务被取消或完成,重新调度...");
|
||||
// 重新启动任务
|
||||
run(null);
|
||||
break;
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
log.warn("监控线程被中断");
|
||||
break;
|
||||
} catch (Exception e) {
|
||||
log.error("监控任务异常", e);
|
||||
}
|
||||
}
|
||||
}, "Schedule-Monitor-Thread");
|
||||
|
||||
monitorThread.setDaemon(true);
|
||||
monitorThread.start();
|
||||
}
|
||||
|
||||
private void executeScheduledTask() {
|
||||
log.info("轮询定时任务执行中!");
|
||||
List<CsEquipmentDeliveryPO> list = csEquipmentDeliveryService.getOfflineDev();
|
||||
if (CollUtil.isNotEmpty(list)) {
|
||||
ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||
try {
|
||||
List<List<CsEquipmentDeliveryPO>> subLists = CollUtil.split(list, 10);
|
||||
// List<List<CsEquipmentDeliveryPO>> subLists = new ArrayList<>();
|
||||
// int partitionSize = list.size() / 10;
|
||||
// for (int i = 0; i < 10; i++) {
|
||||
// int start = i * partitionSize;
|
||||
// int end = (i == 9) ? list.size() : start + partitionSize;
|
||||
// subLists.add(list.subList(start, end));
|
||||
// }
|
||||
// 创建一个ExecutorService来处理这些任务
|
||||
List<Future<Void>> futures = new ArrayList<>();
|
||||
// 提交任务给线程池执行
|
||||
// for (int i = 0; i < 10; i++) {
|
||||
// int index = i;
|
||||
// futures.add(executor.submit(() -> {
|
||||
// accessDev(subLists.get(index));
|
||||
// return null;
|
||||
// }));
|
||||
// }
|
||||
for (List<CsEquipmentDeliveryPO> subList : subLists) {
|
||||
futures.add(executor.submit(() -> {
|
||||
accessDev(subList);
|
||||
try {
|
||||
accessDevSafely(subList); // 使用安全版本
|
||||
} catch (Exception e) {
|
||||
log.error("处理设备子列表异常", e);
|
||||
}
|
||||
return null;
|
||||
}));
|
||||
}
|
||||
// 等待所有任务完成
|
||||
for (Future<Void> future : futures) {
|
||||
try {
|
||||
future.get();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
log.error("任务被中断", e);
|
||||
} catch (ExecutionException e) {
|
||||
log.error("任务执行异常", e.getCause());
|
||||
future.get(5, TimeUnit.MINUTES);
|
||||
} catch (TimeoutException e) {
|
||||
log.error("任务执行超时", e);
|
||||
} catch (Exception e) {
|
||||
log.error("任务执行异常", e);
|
||||
}
|
||||
}
|
||||
// 关闭ExecutorService
|
||||
} finally {
|
||||
executor.shutdown();
|
||||
}
|
||||
};
|
||||
//第一次执行的时间为120s,然后在前一个任务执行完毕后,等待120s再执行下一个任务
|
||||
scheduler.scheduleWithFixedDelay(task, AUTO_TIME, AUTO_TIME, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
public void accessDev(List<CsEquipmentDeliveryPO> list) {
|
||||
if (CollUtil.isNotEmpty(list)) {
|
||||
try {
|
||||
list.forEach(item -> {
|
||||
System.out.println(Thread.currentThread().getName() + ": auto : nDid : " + item.getNdid());
|
||||
//判断设备类型 便携式设备需要特殊处理 未注册的要先注册、再接入;已注册的直接重新接入
|
||||
String code = dictTreeFeignClient.queryById(item.getDevType()).getData().getCode();
|
||||
if (Objects.equals(code, DicDataEnum.PORTABLE.getCode()) && Objects.equals(item.getStatus(), 1)) {
|
||||
//csDeviceService.wlDevRegister(item.getNdid());
|
||||
log.info("请先手动注册、接入");
|
||||
} else {
|
||||
String version = csTopicService.getVersion(item.getNdid());
|
||||
if (Objects.isNull(version)) {
|
||||
version = "V1";
|
||||
}
|
||||
csDeviceService.autoAccess(item.getNdid(), version, 1);
|
||||
try {
|
||||
if (!executor.awaitTermination(1, TimeUnit.MINUTES)) {
|
||||
executor.shutdownNow();
|
||||
}
|
||||
redisUtil.saveByKey(AppRedisKey.DEVICE_MID + item.getNdid(), 1);
|
||||
});
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage());
|
||||
} catch (InterruptedException e) {
|
||||
executor.shutdownNow();
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//安全的accessDev版本
|
||||
private void accessDevSafely(List<CsEquipmentDeliveryPO> list) {
|
||||
if (CollUtil.isNotEmpty(list)) {
|
||||
for (CsEquipmentDeliveryPO item : list) {
|
||||
try {
|
||||
processSingleDevice(item);
|
||||
} catch (Exception e) {
|
||||
log.error("处理设备 {} 失败: {}", item.getNdid(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void processSingleDevice(CsEquipmentDeliveryPO item) {
|
||||
System.out.println(Thread.currentThread().getName() + ": auto : nDid : " + item.getNdid());
|
||||
String code = dictTreeFeignClient.queryById(item.getDevType()).getData().getCode();
|
||||
if (Objects.equals(code, DicDataEnum.PORTABLE.getCode()) && Objects.equals(item.getStatus(), 1)) {
|
||||
log.info("设备 {} 需要手动注册、接入", item.getNdid());
|
||||
} else {
|
||||
String version = csTopicService.getVersion(item.getNdid());
|
||||
if (Objects.isNull(version)) {
|
||||
version = "V1";
|
||||
}
|
||||
// 使用try-catch确保单个设备失败不影响其他设备
|
||||
try {
|
||||
boolean success = csDeviceService.autoAccess2(item.getNdid(), version, 1);
|
||||
if (success) {
|
||||
redisUtil.saveByKey(AppRedisKey.DEVICE_MID + item.getNdid(), 1);
|
||||
} else {
|
||||
log.warn("设备 {} 接入失败", item.getNdid());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("设备 {} 接入异常: {}", item.getNdid(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// @Override
|
||||
// public void run(ApplicationArguments args) {
|
||||
// if (scheduler.isShutdown() || scheduler.isTerminated()) {
|
||||
// scheduler = Executors.newScheduledThreadPool(1);
|
||||
// }
|
||||
// Runnable task = () -> {
|
||||
// log.info("轮询定时任务执行中!");
|
||||
// List<CsEquipmentDeliveryPO> list = csEquipmentDeliveryService.getOfflineDev();
|
||||
// if (CollUtil.isNotEmpty(list)) {
|
||||
// ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||
// // 将任务平均分配给10个子列表
|
||||
// List<List<CsEquipmentDeliveryPO>> subLists = CollUtil.split(list, 10);
|
||||
// // 创建一个ExecutorService来处理这些任务
|
||||
// List<Future<Void>> futures = new ArrayList<>();
|
||||
// for (List<CsEquipmentDeliveryPO> subList : subLists) {
|
||||
// futures.add(executor.submit(() -> {
|
||||
// try {
|
||||
// accessDev(subList);
|
||||
// } catch (Exception e) {
|
||||
// log.error("处理设备子列表异常,但继续处理其他任务", e);
|
||||
// }
|
||||
// return null;
|
||||
// }));
|
||||
// }
|
||||
// // 等待所有任务完成
|
||||
// for (Future<Void> future : futures) {
|
||||
// try {
|
||||
// future.get();
|
||||
// } catch (InterruptedException e) {
|
||||
// Thread.currentThread().interrupt();
|
||||
// log.error("任务被中断", e);
|
||||
// } catch (ExecutionException e) {
|
||||
// log.error("任务执行异常", e.getCause());
|
||||
// } catch (Exception e) {
|
||||
// log.error("系统异常", e.getCause());
|
||||
// }
|
||||
// }
|
||||
// // 关闭ExecutorService
|
||||
// executor.shutdown();
|
||||
// }
|
||||
// };
|
||||
// //第一次执行的时间为120s,然后在前一个任务执行完毕后,等待120s再执行下一个任务
|
||||
// scheduler.scheduleWithFixedDelay(task, AUTO_TIME, AUTO_TIME, TimeUnit.SECONDS);
|
||||
// }
|
||||
//
|
||||
// public void accessDev(List<CsEquipmentDeliveryPO> list) {
|
||||
// if (CollUtil.isNotEmpty(list)) {
|
||||
// try {
|
||||
// list.forEach(item -> {
|
||||
// System.out.println(Thread.currentThread().getName() + ": auto : nDid : " + item.getNdid());
|
||||
// //判断设备类型 便携式设备需要特殊处理 未注册的要先注册、再接入;已注册的直接重新接入
|
||||
// String code = dictTreeFeignClient.queryById(item.getDevType()).getData().getCode();
|
||||
// if (Objects.equals(code, DicDataEnum.PORTABLE.getCode()) && Objects.equals(item.getStatus(), 1)) {
|
||||
// //csDeviceService.wlDevRegister(item.getNdid());
|
||||
// log.info("请先手动注册、接入");
|
||||
// } else {
|
||||
// String version = csTopicService.getVersion(item.getNdid());
|
||||
// if (Objects.isNull(version)) {
|
||||
// version = "V1";
|
||||
// }
|
||||
// csDeviceService.autoAccess(item.getNdid(), version, 1);
|
||||
// }
|
||||
// redisUtil.saveByKey(AppRedisKey.DEVICE_MID + item.getNdid(), 1);
|
||||
// });
|
||||
// } catch (Exception e) {
|
||||
// log.error(e.getMessage());
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
package com.njcn.access.runner;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import com.njcn.access.service.ICsEquipmentDeliveryService;
|
||||
import com.njcn.csdevice.api.EquipmentFeignClient;
|
||||
import com.njcn.redis.pojo.enums.RedisKeyEnum;
|
||||
import com.njcn.redis.utils.RedisUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
/**
|
||||
* @author xy
|
||||
* 定时轮询离线设备接入
|
||||
*/
|
||||
@Component
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class CldHeartTimer implements ApplicationRunner {
|
||||
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
|
||||
private static final long OUT_TIME = 120L;
|
||||
private final RedisUtil redisUtil;
|
||||
private final ICsEquipmentDeliveryService csEquipmentDeliveryService;
|
||||
private final EquipmentFeignClient equipmentFeignClient;
|
||||
|
||||
@Override
|
||||
public void run(ApplicationArguments args) {
|
||||
if (scheduler.isShutdown() || scheduler.isTerminated()) {
|
||||
scheduler = Executors.newScheduledThreadPool(1);
|
||||
}
|
||||
Runnable task = () -> {
|
||||
try {
|
||||
executeScheduledTask();
|
||||
}
|
||||
// 捕获所有Throwable,包括Error
|
||||
catch (Throwable t) {
|
||||
log.error("定时任务发生严重异常,尝试恢复", t);
|
||||
// 可以添加重启逻辑或告警
|
||||
}
|
||||
};
|
||||
ScheduledFuture<?> future = scheduler.scheduleWithFixedDelay(task, OUT_TIME, OUT_TIME, TimeUnit.SECONDS);
|
||||
// 添加监控,如果任务被取消则重新调度
|
||||
monitorScheduledTask(future);
|
||||
}
|
||||
|
||||
//10分钟检查一下调度任务
|
||||
private void monitorScheduledTask(ScheduledFuture<?> future) {
|
||||
Thread monitorThread = new Thread(() -> {
|
||||
while (!Thread.currentThread().isInterrupted()) {
|
||||
try {
|
||||
//每10分钟检查一次
|
||||
Thread.sleep(600000);
|
||||
if (future.isCancelled() || future.isDone()) {
|
||||
log.warn("定时任务被取消或完成,重新调度...");
|
||||
// 重新启动任务
|
||||
run(null);
|
||||
break;
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
log.warn("监控线程被中断");
|
||||
break;
|
||||
} catch (Exception e) {
|
||||
log.error("监控任务异常", e);
|
||||
}
|
||||
}
|
||||
}, "Schedule-Monitor-Thread");
|
||||
monitorThread.setDaemon(true);
|
||||
monitorThread.start();
|
||||
}
|
||||
|
||||
private void executeScheduledTask() {
|
||||
log.info("定时检查云前置心跳!");
|
||||
//获取在运设备的所有前置和进程号,循环查询redis里面是否存在,不存在则将所有前置下的设备翻转
|
||||
List<String> list = csEquipmentDeliveryService.getFrontAndProcess();
|
||||
if (CollUtil.isNotEmpty(list)) {
|
||||
ExecutorService executor = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
List<List<String>> subLists = CollUtil.split(list, 2);
|
||||
List<Future<Void>> futures = new ArrayList<>();
|
||||
for (List<String> subList : subLists) {
|
||||
futures.add(executor.submit(() -> {
|
||||
try {
|
||||
accessDevSafely(subList);
|
||||
} catch (Exception e) {
|
||||
log.error("处理设备子列表异常", e);
|
||||
}
|
||||
return null;
|
||||
}));
|
||||
}
|
||||
for (Future<Void> future : futures) {
|
||||
try {
|
||||
future.get(5, TimeUnit.MINUTES);
|
||||
} catch (TimeoutException e) {
|
||||
log.error("任务执行超时", e);
|
||||
} catch (Exception e) {
|
||||
log.error("任务执行异常", e);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
executor.shutdown();
|
||||
try {
|
||||
if (!executor.awaitTermination(1, TimeUnit.MINUTES)) {
|
||||
executor.shutdownNow();
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
executor.shutdownNow();
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//安全的accessDev版本
|
||||
private void accessDevSafely(List<String> list) {
|
||||
if (CollUtil.isNotEmpty(list)) {
|
||||
for (String item : list) {
|
||||
try {
|
||||
processSingleDevice(item);
|
||||
} catch (Exception e) {
|
||||
log.error("处理设备 {} 失败: {}", item, e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void processSingleDevice(String item) {
|
||||
Object object = redisUtil.getObjectByKey(RedisKeyEnum.CLD_HEART_BEAT_KEY.getKey() + item);
|
||||
if (Objects.isNull(object)) {
|
||||
String nodeId = item.substring(0, item.length() - 1);
|
||||
int processNo = Integer.parseInt(item.substring(item.length() - 1));
|
||||
equipmentFeignClient.updateCldDevStatus(nodeId,processNo);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -21,4 +21,6 @@ public interface AskDeviceDataService {
|
||||
* 实时数据请求报文
|
||||
*/
|
||||
void askRealData(String nDid, Integer idx, Integer size);
|
||||
|
||||
void askCldRealData(String devId, String lineId, String nodeId, Integer idx);
|
||||
}
|
||||
|
||||
@@ -69,4 +69,9 @@ public interface ICsEquipmentDeliveryService extends IService<CsEquipmentDeliver
|
||||
* 获取离线、启用、客户端在线的装置
|
||||
*/
|
||||
List<CsEquipmentDeliveryPO> getOfflineDev();
|
||||
|
||||
/**
|
||||
* 获取在运且在线的装置 所属前置和进程号
|
||||
*/
|
||||
List<String> getFrontAndProcess();
|
||||
}
|
||||
|
||||
@@ -11,6 +11,8 @@ import com.njcn.access.pojo.dto.ReqAndResDto;
|
||||
import com.njcn.access.service.AskDeviceDataService;
|
||||
import com.njcn.common.pojo.exception.BusinessException;
|
||||
import com.njcn.csdevice.enums.AlgorithmResponseEnum;
|
||||
import com.njcn.mq.message.RealDataMessage;
|
||||
import com.njcn.mq.template.RealDataMessageTemplate;
|
||||
import com.njcn.redis.pojo.enums.AppRedisKey;
|
||||
import com.njcn.redis.utils.RedisUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -32,6 +34,7 @@ public class AskDeviceDataServiceImpl implements AskDeviceDataService {
|
||||
private final MqttPublisher publisher;
|
||||
private final CsTopicFeignClient csTopicFeignClient;
|
||||
private final RedisUtil redisUtil;
|
||||
private final RealDataMessageTemplate realDataMessageTemplate;
|
||||
private static Integer mid = 1;
|
||||
private static Integer range = 51200;
|
||||
|
||||
@@ -209,6 +212,18 @@ public class AskDeviceDataServiceImpl implements AskDeviceDataService {
|
||||
redisUtil.saveByKey(AppRedisKey.DEVICE_MID + nDid,mid);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void askCldRealData(String devId, String lineId, String nodeId, Integer idx) {
|
||||
RealDataMessage realDataMessage = new RealDataMessage();
|
||||
realDataMessage.setDevSeries(devId);
|
||||
int lastDigit = Character.getNumericValue(lineId.charAt(lineId.length() - 1));
|
||||
realDataMessage.setLine(lastDigit);
|
||||
realDataMessage.setRealData(true);
|
||||
realDataMessage.setSoeData(true);
|
||||
realDataMessage.setLimit(20);
|
||||
realDataMessage.setIdx(idx);
|
||||
realDataMessageTemplate.sendMember(realDataMessage,nodeId);
|
||||
}
|
||||
|
||||
public Object getDeviceMid(String nDid) {
|
||||
return redisUtil.getObjectByKey(AppRedisKey.DEVICE_MID + nDid);
|
||||
|
||||
@@ -2,7 +2,9 @@ package com.njcn.access.service.impl;
|
||||
|
||||
import cn.hutool.core.collection.CollectionUtil;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.alibaba.nacos.shaded.com.google.gson.Gson;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.github.tocrhz.mqtt.publisher.MqttPublisher;
|
||||
import com.njcn.access.enums.AccessEnum;
|
||||
import com.njcn.access.enums.AccessResponseEnum;
|
||||
@@ -20,11 +22,13 @@ import com.njcn.access.utils.CRC32Utils;
|
||||
import com.njcn.access.utils.JsonUtil;
|
||||
import com.njcn.common.pojo.dto.DeviceLogDTO;
|
||||
import com.njcn.common.pojo.exception.BusinessException;
|
||||
import com.njcn.csdevice.api.CsLogsFeignClient;
|
||||
import com.njcn.csdevice.api.DevModelFeignClient;
|
||||
import com.njcn.csdevice.api.*;
|
||||
import com.njcn.csdevice.enums.AlgorithmResponseEnum;
|
||||
import com.njcn.csdevice.pojo.param.CsDevModelAddParm;
|
||||
import com.njcn.csdevice.pojo.po.*;
|
||||
import com.njcn.csdevice.pojo.po.CsDataArray;
|
||||
import com.njcn.csdevice.pojo.po.CsDataSet;
|
||||
import com.njcn.csdevice.pojo.po.CsDevModelPO;
|
||||
import com.njcn.csdevice.pojo.po.CsEquipmentDeliveryPO;
|
||||
import com.njcn.oss.constant.OssPath;
|
||||
import com.njcn.oss.utils.FileStorageUtil;
|
||||
import com.njcn.redis.pojo.enums.AppRedisKey;
|
||||
@@ -45,7 +49,6 @@ import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.sql.Date;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
@@ -77,6 +80,9 @@ public class CsDevModelServiceImpl implements ICsDevModelService {
|
||||
private final MqttPublisher publisher;
|
||||
private final ICsTopicService csTopicService;
|
||||
private final RedisUtil redisUtil;
|
||||
private final EquipmentFeignClient eequipmentFeignClient;
|
||||
private final DevModelRelationFeignClient devModelRelationFeignClient;
|
||||
private final CsLineFeignClient csLineFeignClient;
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
@@ -96,6 +102,14 @@ public class CsDevModelServiceImpl implements ICsDevModelService {
|
||||
DictTreeVO dictTreeVO = dictTreeFeignClient.queryByCode(devType).getData();
|
||||
if (Objects.isNull(dictTreeVO)){
|
||||
throw new BusinessException(AccessResponseEnum.DEV_TYPE_NOT_FIND);
|
||||
} else if (Objects.equals(devType,DicDataEnum.DEV_CLD.getCode())) {
|
||||
//查询是否已存在云前置模板
|
||||
LambdaQueryWrapper<CsDevModelPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
|
||||
lambdaQueryWrapper.eq(CsDevModelPO::getName,DicDataEnum.DEV_CLD.getCode()).eq(CsDevModelPO::getStatus,1);
|
||||
List<CsDevModelPO> list = csDevModelMapper.selectList(lambdaQueryWrapper);
|
||||
if (CollectionUtil.isNotEmpty(list)) {
|
||||
throw new BusinessException(AccessResponseEnum.CLD_MODEL_EXIST);
|
||||
}
|
||||
}
|
||||
logDto.setOperate("新增设备模板,模板名称:" + templateDto.getDevType());
|
||||
//模板文件存入文件服务器
|
||||
@@ -106,6 +120,21 @@ public class CsDevModelServiceImpl implements ICsDevModelService {
|
||||
analysisDataSet(templateDto,csDevModelPo.getId());
|
||||
//3.录入监测点模板表(记录当前模板有几个监测点,治理类型的模板目前规定1个监测点,电能质量模板根据逻辑子设备来)
|
||||
addCsLineModel(templateDto,csDevModelPo.getId());
|
||||
//4.如果是云前置的模板录入,重新录入完需要将模板关系信息重新录入
|
||||
if (Objects.equals(devType,DicDataEnum.DEV_CLD.getCode())) {
|
||||
List<CsEquipmentDeliveryPO> list = eequipmentFeignClient.getAll().getData();
|
||||
if (CollectionUtil.isNotEmpty(list)) {
|
||||
List<String> devList = list.stream()
|
||||
.filter(item -> Objects.equals(item.getDevAccessMethod(),"CLD"))
|
||||
.map(CsEquipmentDeliveryPO::getId)
|
||||
.collect(Collectors.toList());
|
||||
devModelRelationFeignClient.updateDataByList(devList,csDevModelPo.getId());
|
||||
Object object = redisUtil.getObjectByKey("setId:" + csDevModelPo.getId());
|
||||
if (ObjectUtil.isNotNull(object)) {
|
||||
csLineFeignClient.updateDataByList(devList,csDevModelPo.getId(),object.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
csLogsFeignClient.addUserLog(logDto);
|
||||
} catch (Exception e) {
|
||||
logDto.setResult(0);
|
||||
@@ -373,9 +402,9 @@ public class CsDevModelServiceImpl implements ICsDevModelService {
|
||||
}
|
||||
eleEpdPqdParam.setClassId(classId);
|
||||
if (!Objects.isNull(apf.getHarmStart())){
|
||||
if (Objects.equals(apf.getHarmStart(),0.5) && Objects.equals(apf.getHarmEnd(),49.5)){
|
||||
if (Objects.equals(apf.getHarmStart(),0.5)){
|
||||
eleEpdPqdParam.setHarmStart((int)(apf.getHarmStart()+0.5));
|
||||
eleEpdPqdParam.setHarmEnd((int)(apf.getHarmEnd()+49.5));
|
||||
eleEpdPqdParam.setHarmEnd((int)(apf.getHarmEnd()+0.5));
|
||||
} else {
|
||||
eleEpdPqdParam.setHarmStart((int)(apf.getHarmStart()*1.0));
|
||||
eleEpdPqdParam.setHarmEnd((int)(apf.getHarmEnd()*1.0));
|
||||
@@ -612,9 +641,9 @@ public class CsDevModelServiceImpl implements ICsDevModelService {
|
||||
}
|
||||
eleEpdPqdParam.setUnit(epd.getUnit());
|
||||
if (!Objects.isNull(epd.getHarmStart())){
|
||||
if (Objects.equals(epd.getHarmStart(),0.5) && Objects.equals(epd.getHarmEnd(),49.5)){
|
||||
if (Objects.equals(epd.getHarmStart(),0.5)){
|
||||
eleEpdPqdParam.setHarmStart((int)(epd.getHarmStart()+0.5));
|
||||
eleEpdPqdParam.setHarmEnd((int)(epd.getHarmEnd()+49.5));
|
||||
eleEpdPqdParam.setHarmEnd((int)(epd.getHarmEnd()+0.5));
|
||||
} else {
|
||||
eleEpdPqdParam.setHarmStart((int)(epd.getHarmStart()*1.0));
|
||||
eleEpdPqdParam.setHarmEnd((int)(epd.getHarmEnd()*1.0));
|
||||
@@ -648,14 +677,15 @@ public class CsDevModelServiceImpl implements ICsDevModelService {
|
||||
}
|
||||
eleEpdPqdParam.setUnit(pqd.getUnit());
|
||||
if (!Objects.isNull(pqd.getHarmStart())){
|
||||
if (Objects.equals(pqd.getHarmStart(),0.5) && Objects.equals(pqd.getHarmEnd(),49.5)){
|
||||
if (Objects.equals(pqd.getHarmStart(),0.5)){
|
||||
eleEpdPqdParam.setHarmStart((int)(pqd.getHarmStart()+0.5));
|
||||
eleEpdPqdParam.setHarmEnd((int)(pqd.getHarmEnd()+49.5));
|
||||
eleEpdPqdParam.setHarmEnd((int)(pqd.getHarmEnd()+0.5));
|
||||
} else {
|
||||
eleEpdPqdParam.setHarmStart((int)(pqd.getHarmStart()*1.0));
|
||||
eleEpdPqdParam.setHarmEnd((int)(pqd.getHarmEnd()*1.0));
|
||||
}
|
||||
}
|
||||
eleEpdPqdParam.setStatMethod(pqd.getStatMethod());
|
||||
eleEpdPqdParam.setDataType(id);
|
||||
eleEpdPqdParam.setClassId(classId);
|
||||
result.add(eleEpdPqdParam);
|
||||
@@ -839,12 +869,18 @@ public class CsDevModelServiceImpl implements ICsDevModelService {
|
||||
* 解析数据集、详细数据
|
||||
*/
|
||||
private void analysisDataSet(TemplateDto templateDto,String pId){
|
||||
String code;
|
||||
List<CsDataSet> setList = new ArrayList<>();
|
||||
List<CsDataArray> arrayList = new ArrayList<>();
|
||||
List<DataSetDto> dataSetList = templateDto.getDataSet();
|
||||
String devType = templateDto.getDevType();
|
||||
DictTreeVO dictTreeVO = dictTreeFeignClient.queryByCode(devType).getData();
|
||||
String code = dictTreeFeignClient.queryById(dictTreeVO.getPid()).getData().getCode();
|
||||
if (!DicDataEnum.DEV_CLD.getCode().equals(devType)){
|
||||
DictTreeVO dictTreeVO = dictTreeFeignClient.queryByCode(devType).getData();
|
||||
code = dictTreeFeignClient.queryById(dictTreeVO.getPid()).getData().getCode();
|
||||
} else {
|
||||
code = null;
|
||||
}
|
||||
|
||||
//逻辑设备录入
|
||||
if (CollectionUtil.isNotEmpty(dataSetList)){
|
||||
dataSetList.forEach(item1->{
|
||||
@@ -927,40 +963,46 @@ public class CsDevModelServiceImpl implements ICsDevModelService {
|
||||
}
|
||||
if(CollectionUtil.isNotEmpty(setList)) {
|
||||
csDataSetService.addList(setList);
|
||||
setList.forEach(item->{
|
||||
if (Objects.equals(item.getName(),"统计数据")) {
|
||||
redisUtil.saveByKeyWithExpire("setId:" + pId,item.getId(),30L);
|
||||
}
|
||||
});
|
||||
}
|
||||
if(CollectionUtil.isNotEmpty(arrayList)) {
|
||||
csDataArrayService.addList(arrayList);
|
||||
List<CsGroup> ls = new ArrayList<>();
|
||||
List<CsGroArr> groArrList = new ArrayList<>();
|
||||
Map<String,List<CsDataArray>> setMap = arrayList.stream().collect(Collectors.groupingBy(CsDataArray::getPid,LinkedHashMap::new,Collectors.toList()));
|
||||
setMap.forEach((k0,v0)->{
|
||||
AtomicReference<Integer> sort = new AtomicReference<>(0);
|
||||
Map<String,List<CsDataArray>> map = v0.stream().filter(a-> "avg".equals(a.getStatMethod()) || Objects.isNull(a.getStatMethod())).collect(Collectors.groupingBy(CsDataArray::getAnotherName,LinkedHashMap::new,Collectors.toList()));
|
||||
map.forEach((k,v)->{
|
||||
//录入组数据
|
||||
String groupId = IdUtil.simpleUUID();
|
||||
CsGroup csGroup = new CsGroup();
|
||||
csGroup.setId(groupId);
|
||||
csGroup.setDataSetId(k0);
|
||||
csGroup.setGroupName(k);
|
||||
csGroup.setSort(sort.getAndSet(sort.get() + 1));
|
||||
csGroup.setIsShow(1);
|
||||
ls.add(csGroup);
|
||||
//录入组和指标关系
|
||||
v.forEach(item->{
|
||||
CsGroArr csGroArr = new CsGroArr();
|
||||
csGroArr.setGroupId(groupId);
|
||||
csGroArr.setArrayId(item.getId());
|
||||
groArrList.add(csGroArr);
|
||||
});
|
||||
});
|
||||
});
|
||||
if(CollectionUtil.isNotEmpty(ls)) {
|
||||
csGroupService.addList(ls);
|
||||
}
|
||||
if(CollectionUtil.isNotEmpty(groArrList)) {
|
||||
csGroArrService.addGroArrList(groArrList);
|
||||
}
|
||||
//物联这边没有分组的要求,这部分代码先注释,用能那边用到这个代码
|
||||
// List<CsGroup> ls = new ArrayList<>();
|
||||
// List<CsGroArr> groArrList = new ArrayList<>();
|
||||
// Map<String,List<CsDataArray>> setMap = arrayList.stream().collect(Collectors.groupingBy(CsDataArray::getPid,LinkedHashMap::new,Collectors.toList()));
|
||||
// setMap.forEach((k0,v0)->{
|
||||
// AtomicReference<Integer> sort = new AtomicReference<>(0);
|
||||
// Map<String,List<CsDataArray>> map = v0.stream().filter(a-> "avg".equals(a.getStatMethod()) || Objects.isNull(a.getStatMethod())).collect(Collectors.groupingBy(CsDataArray::getAnotherName,LinkedHashMap::new,Collectors.toList()));
|
||||
// map.forEach((k,v)->{
|
||||
// //录入组数据
|
||||
// String groupId = IdUtil.simpleUUID();
|
||||
// CsGroup csGroup = new CsGroup();
|
||||
// csGroup.setId(groupId);
|
||||
// csGroup.setDataSetId(k0);
|
||||
// csGroup.setGroupName(k);
|
||||
// csGroup.setSort(sort.getAndSet(sort.get() + 1));
|
||||
// csGroup.setIsShow(1);
|
||||
// ls.add(csGroup);
|
||||
// //录入组和指标关系
|
||||
// v.forEach(item->{
|
||||
// CsGroArr csGroArr = new CsGroArr();
|
||||
// csGroArr.setGroupId(groupId);
|
||||
// csGroArr.setArrayId(item.getId());
|
||||
// groArrList.add(csGroArr);
|
||||
// });
|
||||
// });
|
||||
// });
|
||||
// if(CollectionUtil.isNotEmpty(ls)) {
|
||||
// csGroupService.addList(ls);
|
||||
// }
|
||||
// if(CollectionUtil.isNotEmpty(groArrList)) {
|
||||
// csGroArrService.addGroArrList(groArrList);
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -371,7 +371,7 @@ public class CsDeviceServiceImpl implements ICsDeviceService {
|
||||
}
|
||||
|
||||
@Override
|
||||
// @Transactional(rollbackFor = Exception.class)
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public String wlDevRegister(String nDid) {
|
||||
String result = "fail";
|
||||
// 设备状态判断
|
||||
@@ -404,7 +404,7 @@ public class CsDeviceServiceImpl implements ICsDeviceService {
|
||||
Thread.sleep(2000);
|
||||
List<CsModelDto> modelList = channelObjectUtil.objectToList(redisUtil.getObjectByKey(AppRedisKey.MODEL + nDid),CsModelDto.class);
|
||||
if (CollUtil.isEmpty(modelList)) {
|
||||
throwExceptionAndLog(AccessResponseEnum.MODEL_ERROR, logDto);
|
||||
throwExceptionAndLog(nDid,AccessResponseEnum.MODEL_ERROR, logDto);
|
||||
}
|
||||
List<CsDataSet> list = csDataSetService.getDataSetData(modelList.get(0).getModelId());
|
||||
list.forEach(item->{
|
||||
@@ -459,6 +459,7 @@ public class CsDeviceServiceImpl implements ICsDeviceService {
|
||||
logDto.setResult(0);
|
||||
logDto.setFailReason(e.getMessage());
|
||||
csLogsFeignClient.addUserLog(logDto);
|
||||
resetFactory(nDid);
|
||||
throw new BusinessException(AccessResponseEnum.ACCESS_ERROR);
|
||||
}
|
||||
return result;
|
||||
@@ -478,18 +479,18 @@ public class CsDeviceServiceImpl implements ICsDeviceService {
|
||||
DeviceLogDTO logDto = createLogDto("当前设备"+nDid+"状态判断");
|
||||
CsEquipmentDeliveryVO csEquipmentDeliveryVO = csEquipmentDeliveryService.queryEquipmentBynDid(nDid);
|
||||
if (Objects.isNull(csEquipmentDeliveryVO.getNdid())) {
|
||||
throwExceptionAndLog(AccessResponseEnum.NDID_NO_FIND, logDto);
|
||||
throwExceptionAndLog(nDid,AccessResponseEnum.NDID_NO_FIND, logDto);
|
||||
}
|
||||
SysDicTreePO sysDicTreePo = dictTreeFeignClient.queryById(csEquipmentDeliveryVO.getDevType()).getData();
|
||||
if (Objects.isNull(sysDicTreePo)) {
|
||||
throwExceptionAndLog(AccessResponseEnum.DEV_NOT_FIND, logDto);
|
||||
throwExceptionAndLog(nDid,AccessResponseEnum.DEV_NOT_FIND, logDto);
|
||||
}
|
||||
String code = sysDicTreePo.getCode();
|
||||
if (!Objects.equals(code, DicDataEnum.PORTABLE.getCode())) {
|
||||
throwExceptionAndLog(AccessResponseEnum.DEV_IS_NOT_PORTABLE, logDto);
|
||||
throwExceptionAndLog(nDid,AccessResponseEnum.DEV_IS_NOT_PORTABLE, logDto);
|
||||
}
|
||||
if (!mqttUtil.judgeClientOnline("NJCN-" + nDid.substring(nDid.length() - 6))) {
|
||||
throwExceptionAndLog(AccessResponseEnum.MISSING_CLIENT, logDto);
|
||||
throwExceptionAndLog(nDid,AccessResponseEnum.MISSING_CLIENT, logDto);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -503,7 +504,7 @@ public class CsDeviceServiceImpl implements ICsDeviceService {
|
||||
CsEquipmentDeliveryVO csEquipmentDeliveryVO = csEquipmentDeliveryService.queryEquipmentBynDid(nDid);
|
||||
SysDicTreePO dictData = dictTreeFeignClient.queryById(csEquipmentDeliveryVO.getDevModel()).getData();
|
||||
if (Objects.isNull(dictData)) {
|
||||
throwExceptionAndLog(AccessResponseEnum.DEV_MODEL_NOT_FIND, logDto);
|
||||
throwExceptionAndLog(nDid,AccessResponseEnum.DEV_MODEL_NOT_FIND, logDto);
|
||||
}
|
||||
String devModel = dictData.getCode();
|
||||
zhiLianRegister(nDid,devModel);
|
||||
@@ -518,10 +519,11 @@ public class CsDeviceServiceImpl implements ICsDeviceService {
|
||||
return logDto;
|
||||
}
|
||||
|
||||
private void throwExceptionAndLog(AccessResponseEnum responseEnum, DeviceLogDTO logDto) {
|
||||
private void throwExceptionAndLog(String nDid,AccessResponseEnum responseEnum, DeviceLogDTO logDto) {
|
||||
logDto.setResult(0);
|
||||
logDto.setFailReason(responseEnum.getMessage());
|
||||
csLogsFeignClient.addUserLog(logDto);
|
||||
resetFactory(nDid);
|
||||
throw new BusinessException(responseEnum);
|
||||
}
|
||||
|
||||
@@ -604,20 +606,20 @@ public class CsDeviceServiceImpl implements ICsDeviceService {
|
||||
*/
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean autoAccess(String nDid,String version,Integer mid) {
|
||||
String clientName = "NJCN-" + nDid.substring(nDid.length() - 6);
|
||||
boolean mqttClient = mqttUtil.judgeClientOnline(clientName);
|
||||
if (!mqttClient) {
|
||||
DeviceLogDTO logDto = new DeviceLogDTO();
|
||||
logDto.setUserName("运维管理员");
|
||||
logDto.setLoginName("njcnyw");
|
||||
logDto.setResult(1);
|
||||
logDto.setOperate(nDid + "接入失败,装置客户端不在线");
|
||||
csLogsFeignClient.addUserLog(logDto);
|
||||
throw new BusinessException(AlgorithmResponseEnum.DEV_OFFLINE);
|
||||
}
|
||||
boolean result = false;
|
||||
Map<Integer,String> modelMap = new HashMap<>();
|
||||
try {
|
||||
String clientName = "NJCN-" + nDid.substring(nDid.length() - 6);
|
||||
boolean mqttClient = mqttUtil.judgeClientOnline(clientName);
|
||||
if (!mqttClient) {
|
||||
DeviceLogDTO logDto = new DeviceLogDTO();
|
||||
logDto.setUserName("运维管理员");
|
||||
logDto.setLoginName("njcnyw");
|
||||
logDto.setResult(1);
|
||||
logDto.setOperate(nDid + "接入失败,装置客户端不在线");
|
||||
csLogsFeignClient.addUserLog(logDto);
|
||||
throw new BusinessException(AlgorithmResponseEnum.DEV_OFFLINE);
|
||||
}
|
||||
Map<Integer,String> modelMap = new HashMap<>();
|
||||
//删除缓存数据
|
||||
redisUtil.delete(AppRedisKey.MODEL + nDid);
|
||||
redisUtil.deleteKeysByString(AppRedisKey.DEV_MODEL);
|
||||
@@ -669,6 +671,77 @@ public class CsDeviceServiceImpl implements ICsDeviceService {
|
||||
return result;
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean autoAccess2(String nDid, String version, Integer mid) {
|
||||
boolean result = false;
|
||||
try {
|
||||
String clientName = "NJCN-" + nDid.substring(nDid.length() - 6);
|
||||
boolean mqttClient = mqttUtil.judgeClientOnline(clientName);
|
||||
if (!mqttClient) {
|
||||
DeviceLogDTO logDto = new DeviceLogDTO();
|
||||
logDto.setUserName("运维管理员");
|
||||
logDto.setLoginName("njcnyw");
|
||||
logDto.setResult(1);
|
||||
logDto.setOperate(nDid + "接入失败,装置客户端不在线");
|
||||
csLogsFeignClient.addUserLog(logDto);
|
||||
// 改为返回false而不是抛出异常
|
||||
log.warn("设备 {} 客户端不在线", nDid);
|
||||
return false;
|
||||
}
|
||||
|
||||
Map<Integer, String> modelMap = new HashMap<>();
|
||||
redisUtil.delete(AppRedisKey.MODEL + nDid);
|
||||
redisUtil.deleteKeysByString(AppRedisKey.DEV_MODEL);
|
||||
publisher.send("/Pfm/DevCmd/"+version+"/"+nDid, new Gson().toJson(getJson(mid,TypeEnum.TYPE_3.getCode())), 1, false);
|
||||
try {
|
||||
Thread.sleep(2000);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
log.warn("线程休眠被中断: {}", e.getMessage());
|
||||
return false;
|
||||
}
|
||||
List<CsModelDto> modelId = channelObjectUtil.objectToList(redisUtil.getObjectByKey(AppRedisKey.MODEL + nDid), CsModelDto.class);
|
||||
if (CollUtil.isEmpty(modelId)) {
|
||||
log.warn("设备 {} 未获取到模板信息", nDid);
|
||||
return false;
|
||||
}
|
||||
CsEquipmentDeliveryVO vo = equipmentFeignClient.queryEquipmentByndid(nDid).getData();
|
||||
for (CsModelDto item : modelId) {
|
||||
CsDevModelRelationPO po = new CsDevModelRelationPO();
|
||||
po.setDevId(vo.getId());
|
||||
po.setModelId(item.getModelId());
|
||||
po.setDid(item.getDid());
|
||||
po.setUpdateTime(LocalDateTime.now());
|
||||
csDevModelRelationService.addRelation(po);
|
||||
modelMap.put(item.getType(), item.getModelId());
|
||||
}
|
||||
List<CsLinePO> lineList;
|
||||
Object object = redisUtil.getObjectByKey("accessLineInfo:" + nDid);
|
||||
if (Objects.isNull(object)) {
|
||||
lineList = csLineFeignClient.findByNdid(nDid).getData();
|
||||
for (CsLinePO item : lineList) {
|
||||
if (item.getClDid() == 0) {
|
||||
updateLineIds(modelMap.get(0), item.getClDid(), nDid);
|
||||
} else {
|
||||
updateLineIds(modelMap.get(1), item.getClDid(), nDid);
|
||||
}
|
||||
}
|
||||
}
|
||||
publisher.send("/Pfm/DevCmd/"+version+"/"+nDid, new Gson().toJson(getJson(mid,TypeEnum.TYPE_5.getCode())), 1, false);
|
||||
// redisUtil.saveByKeyWithExpire("startFile:" + nDid, null, 60L);
|
||||
result = true;
|
||||
} catch (Exception e) {
|
||||
DeviceLogDTO logDto = new DeviceLogDTO();
|
||||
logDto.setUserName("运维管理员");
|
||||
logDto.setLoginName("njcnyw");
|
||||
logDto.setResult(1);
|
||||
logDto.setOperate(nDid + "装置接入失败");
|
||||
csLogsFeignClient.addUserLog(logDto);
|
||||
log.error("设备 {} 接入失败: {}", nDid, e.getMessage());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装报文
|
||||
*/
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.njcn.access.service.impl;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.njcn.access.enums.AccessEnum;
|
||||
@@ -16,10 +18,8 @@ import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
*
|
||||
@@ -125,6 +125,7 @@ public class CsEquipmentDeliveryServiceImpl extends ServiceImpl<CsEquipmentDeliv
|
||||
.eq(CsEquipmentDeliveryPO::getRunStatus,AccessEnum.OFFLINE.getCode())
|
||||
.eq(CsEquipmentDeliveryPO::getUsageStatus,1)
|
||||
.in(CsEquipmentDeliveryPO::getStatus, Arrays.asList(2,3))
|
||||
.isNull(CsEquipmentDeliveryPO::getNodeId)
|
||||
.list();
|
||||
if (CollUtil.isNotEmpty(list)) {
|
||||
list.forEach(item->{
|
||||
@@ -145,4 +146,18 @@ public class CsEquipmentDeliveryServiceImpl extends ServiceImpl<CsEquipmentDeliv
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getFrontAndProcess() {
|
||||
QueryWrapper<CsEquipmentDeliveryPO> wrapper = new QueryWrapper<>();
|
||||
wrapper.select("DISTINCT CONCAT(node_id, node_process) as concatenated");
|
||||
wrapper.eq("usage_status", 1);
|
||||
wrapper.eq("run_status", 2);
|
||||
wrapper.isNotNull("node_id");
|
||||
return baseMapper.selectObjs(wrapper)
|
||||
.stream()
|
||||
.map(obj -> (String) obj)
|
||||
.distinct()
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,49 +1,37 @@
|
||||
package com.njcn;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import com.alibaba.nacos.shaded.com.google.common.reflect.TypeToken;
|
||||
import com.alibaba.nacos.shaded.com.google.gson.Gson;
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import com.github.tocrhz.mqtt.publisher.MqttPublisher;
|
||||
import com.graphbuilder.math.func.EFunction;
|
||||
import com.njcn.access.AccessBootApplication;
|
||||
import com.njcn.access.enums.AccessEnum;
|
||||
import com.njcn.access.enums.TypeEnum;
|
||||
import com.njcn.access.pojo.dto.ReqAndResDto;
|
||||
import com.njcn.access.pojo.dto.mqtt.MqttClientDto;
|
||||
import com.njcn.access.service.ICsEquipmentDeliveryService;
|
||||
import com.njcn.access.service.ICsTopicService;
|
||||
import com.njcn.access.service.impl.CsDeviceServiceImpl;
|
||||
import com.njcn.access.utils.MqttUtil;
|
||||
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
|
||||
import com.njcn.common.pojo.exception.BusinessException;
|
||||
import com.njcn.common.utils.PubUtils;
|
||||
import com.njcn.csdevice.pojo.po.CsLinePO;
|
||||
import com.njcn.csdevice.pojo.po.CsEquipmentDeliveryPO;
|
||||
import com.njcn.oss.utils.FileStorageUtil;
|
||||
import com.njcn.redis.pojo.enums.AppRedisKey;
|
||||
import com.njcn.redis.utils.RedisUtil;
|
||||
import io.lettuce.core.protocol.CompleteableCommand;
|
||||
import com.njcn.system.api.DictTreeFeignClient;
|
||||
import com.njcn.system.enums.DicDataEnum;
|
||||
import lombok.SneakyThrows;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import okhttp3.Credentials;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
import org.eclipse.paho.client.mqttv3.*;
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.lang.reflect.Array;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.zip.CRC32;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/**
|
||||
* Unit test for simple App.
|
||||
@@ -81,72 +69,410 @@ public class AppTest
|
||||
private MqttUtil mqttUtil;
|
||||
|
||||
@Test
|
||||
public void lossTest() {
|
||||
final int[] mid = {2};
|
||||
for (int i = 0; i < 2; i++) {
|
||||
mid[0] = mid[0] + 1;
|
||||
public void deleteRedis() {
|
||||
redisUtil.deleteKeysByString("devModelKey:00B78DA800B011avg");
|
||||
}
|
||||
ScheduledFuture<?> runnableFuture = null;
|
||||
@Resource
|
||||
private ICsTopicService csTopicService;
|
||||
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
|
||||
ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||
private static final long ACCESS_TIME = 20L;
|
||||
|
||||
@Resource
|
||||
private DictTreeFeignClient dictTreeFeignClient;
|
||||
|
||||
/**
|
||||
* 测试下载文件
|
||||
*/
|
||||
@Test
|
||||
public void run1() {
|
||||
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
|
||||
Runnable task = () -> {
|
||||
System.out.println("轮询定时任务执行中!");
|
||||
};
|
||||
scheduler.scheduleAtFixedRate(task, 0, 1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void run() {
|
||||
Runnable task = () -> {
|
||||
log.info("轮询定时任务执行中!");
|
||||
|
||||
CsEquipmentDeliveryPO po = new CsEquipmentDeliveryPO();
|
||||
po.setNdid("00B78DA80103");
|
||||
po.setDevType("8b45cf6b7f5266e777d07c166ad5fa77");
|
||||
po.setStatus(2);
|
||||
List<CsEquipmentDeliveryPO> list = Collections.singletonList(po);
|
||||
|
||||
if (CollUtil.isNotEmpty(list)) {
|
||||
ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||
// 将任务平均分配给10个子列表
|
||||
List<List<CsEquipmentDeliveryPO>> subLists = new ArrayList<>();
|
||||
int partitionSize = list.size() / 10;
|
||||
for (int i = 0; i < 10; i++) {
|
||||
int start = i * partitionSize;
|
||||
int end = (i == 9) ? list.size() : start + partitionSize;
|
||||
subLists.add(list.subList(start, end));
|
||||
}
|
||||
// 创建一个ExecutorService来处理这些任务
|
||||
List<Future<Void>> futures = new ArrayList<>();
|
||||
// 提交任务给线程池执行
|
||||
for (int i = 0; i < 10; i++) {
|
||||
int index = i;
|
||||
futures.add(executor.submit(new Callable<Void>() {
|
||||
@Override
|
||||
public Void call() {
|
||||
// accessDev(subLists.get(index));
|
||||
System.out.println("123");
|
||||
return null;
|
||||
}
|
||||
}));
|
||||
}
|
||||
// 等待所有任务完成
|
||||
for (Future<Void> future : futures) {
|
||||
try {
|
||||
future.get();
|
||||
} catch (InterruptedException | ExecutionException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
// 关闭ExecutorService
|
||||
executor.shutdown();
|
||||
}
|
||||
};
|
||||
//第一次执行的时间为120s,然后每隔120s执行一次
|
||||
scheduler.scheduleAtFixedRate(task,0,20,TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
public void accessDev(List<CsEquipmentDeliveryPO> list) {
|
||||
if (CollUtil.isNotEmpty(list)) {
|
||||
list.forEach(item->{
|
||||
System.out.println(Thread.currentThread().getName() + ": auto : nDid : " + item.getNdid());
|
||||
//判断设备类型 便携式设备需要特殊处理 未注册的要先注册、再接入;已注册的直接重新接入
|
||||
String code = dictTreeFeignClient.queryById(item.getDevType()).getData().getCode();
|
||||
if (Objects.equals(code, DicDataEnum.PORTABLE.getCode()) && Objects.equals(item.getStatus(),1)) {
|
||||
//csDeviceService.wlDevRegister(item.getNdid());
|
||||
log.info("请先手动注册、接入");
|
||||
} else {
|
||||
String version = csTopicService.getVersion(item.getNdid());
|
||||
if (Objects.isNull(version)) {
|
||||
version = "V1";
|
||||
}
|
||||
csDeviceService.devAccessAskTemplate(item.getNdid(),version,1);
|
||||
}
|
||||
redisUtil.saveByKey(AppRedisKey.DEVICE_MID + item.getNdid(),1);
|
||||
});
|
||||
}
|
||||
System.out.println("mid==:" + mid[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test1() {
|
||||
String clientName = "NJCN-A801C8";
|
||||
boolean mqttClient = mqttUtil.judgeClientOnline(clientName);
|
||||
System.out.println("mqttClient==:" + mqttClient);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
// ReqAndResDto reqAndResParam = new ReqAndResDto();
|
||||
// reqAndResParam.setMid(1);
|
||||
// reqAndResParam.setDid(0);
|
||||
// reqAndResParam.setPri(AccessEnum.FIRST_CHANNEL.getCode());
|
||||
// reqAndResParam.setType(4866);
|
||||
// publisher.send("/Dev/Data1/V1/123", new Gson().toJson(reqAndResParam),1,false);
|
||||
|
||||
// String key = String.valueOf(IdUtil.getSnowflake().nextId());
|
||||
// System.out.println("key==:" + key);
|
||||
|
||||
// List<CsLinePO> csLinePoList = new ArrayList<>();
|
||||
// CsLinePO po1 = new CsLinePO();
|
||||
// po1.setPosition("1");
|
||||
// CsLinePO po2= new CsLinePO();
|
||||
// po2.setPosition("2");
|
||||
// CsLinePO po3= new CsLinePO();
|
||||
// po3.setPosition("3");
|
||||
// CsLinePO po4= new CsLinePO();
|
||||
// po4.setPosition("1");
|
||||
// @Test
|
||||
// public void lossTest() {
|
||||
// final int[] mid = {2};
|
||||
// for (int i = 0; i < 2; i++) {
|
||||
// mid[0] = mid[0] + 1;
|
||||
// }
|
||||
// System.out.println("mid==:" + mid[0]);
|
||||
// }
|
||||
//
|
||||
// csLinePoList.add(po1);
|
||||
// csLinePoList.add(po2);
|
||||
// csLinePoList.add(po3);
|
||||
// csLinePoList.add(po4);
|
||||
// List<String> l = csLinePoList.stream().map(CsLinePO::getPosition).collect(Collectors.toList());
|
||||
// System.out.println("l===:" + l);
|
||||
// List<String> lineList = l.stream().filter(e-> Collections.frequency(l,e) > 1).distinct().collect(Collectors.toList());
|
||||
// System.out.println("lineList==:" + lineList);
|
||||
// @Test
|
||||
// public void test1() {
|
||||
// String clientName = "NJCN-016AB3";
|
||||
// boolean mqttClient = mqttUtil.judgeClientOnline(clientName);
|
||||
// System.out.println("mqttClient==:" + mqttClient);
|
||||
// }
|
||||
//
|
||||
// @Test
|
||||
// public void testAutoAccess() {
|
||||
// List<CsEquipmentDeliveryPO> list = new ArrayList<>();
|
||||
// //项目启动60s后发起自动接入
|
||||
// Runnable task = () -> {
|
||||
// long time1 = System.currentTimeMillis();
|
||||
// List<CsEquipmentDeliveryPO> list1 = csEquipmentDeliveryService.getAll();
|
||||
// for (int i = 0; i < 100; i++) {
|
||||
// list.addAll(list1);
|
||||
// }
|
||||
// if (CollUtil.isNotEmpty(list)) {
|
||||
// // 将任务平均分配给10个子列表
|
||||
// List<List<CsEquipmentDeliveryPO>> subLists = new ArrayList<>();
|
||||
// int partitionSize = list.size() / 10;
|
||||
// for (int i = 0; i < 10; i++) {
|
||||
// int start = i * partitionSize;
|
||||
// int end = (i == 9) ? list.size() : start + partitionSize;
|
||||
// subLists.add(list.subList(start, end));
|
||||
// }
|
||||
//
|
||||
// // 创建一个ExecutorService来处理这些任务
|
||||
// List<Future<Void>> futures = new ArrayList<>();
|
||||
// // 提交任务给线程池执行
|
||||
// for (int i = 0; i < 10; i++) {
|
||||
// int index = i;
|
||||
// futures.add(executor.submit(new Callable<Void>() {
|
||||
// @Override
|
||||
// public Void call() throws Exception {
|
||||
// accessDev(subLists.get(index));
|
||||
// return null;
|
||||
// }
|
||||
// }));
|
||||
// }
|
||||
// // 等待所有任务完成
|
||||
// for (Future<Void> future : futures) {
|
||||
// try {
|
||||
// future.get();
|
||||
// } catch (InterruptedException | ExecutionException e) {
|
||||
// throw new RuntimeException(e);
|
||||
// }
|
||||
// }
|
||||
// // 关闭ExecutorService
|
||||
// executor.shutdown();
|
||||
// scheduler.shutdown();
|
||||
// }
|
||||
// long time2 = System.currentTimeMillis();
|
||||
// System.out.println("执行时间==:" + (time2 - time1));
|
||||
// };
|
||||
// scheduler.schedule(task, ACCESS_TIME, TimeUnit.SECONDS);
|
||||
// }
|
||||
|
||||
// String text = "TkosUFEsMTk5OQ0KNiw2QSwwRA0KMSxBz+C159G5LEEstefRuSxWLDAuMDYyMjU2LDAuMDAwMDAwLDAuMDAwMDAwLC0zMjc2NywzMjc2NywzODAsMzgwLFMNCjIsQs/gtefRuSxCLLXn0bksViwwLjA2MjI1NiwwLjAwMDAwMCwwLjAwMDAwMCwtMzI3NjcsMzI3NjcsMzgwLDM4MCxTDQozLEPP4LXn0bksQyy159G5LFYsMC4wNjIyNTYsMC4wMDAwMDAsMC4wMDAwMDAsLTMyNzY3LDMyNzY3LDM4MCwzODAsUw0KNCxBz+C158H3LEEstefB9yxBLDAuMDE1MjU5LDAuMDAwMDAwLDAuMDAwMDAwLC0zMjc2NywzMjc2NywyMDAsNSxTDQo1LELP4LXnwfcsQiy158H3LEEsMC4wMTUyNTksMC4wMDAwMDAsMC4wMDAwMDAsLTMyNzY3LDMyNzY3LDIwMCw1LFMNCjYsQ8/gtefB9yxDLLXnwfcsQSwwLjAxNTI1OSwwLjAwMDAwMCwwLjAwMDAwMCwtMzI3NjcsMzI3NjcsMjAwLDUsUw0KNTANCjENCjEyODAwLDcxNjgNCjA1LzA5LzIwMjMsMTU6NTQ6MDIuMTM2MDAwDQowNS8wOS8yMDIzLDE1OjU0OjAyLjIzNjAwMA0KQklOQVJZDQoxDQo=";
|
||||
// byte[] byteArray = Base64.getDecoder().decode(text);
|
||||
// InputStream inputStream = new ByteArrayInputStream(byteArray);
|
||||
// fileStorageUtil.uploadStreamSpecifyName(inputStream, "configuration/","xuyang.cfg");
|
||||
// public void accessDev(List<CsEquipmentDeliveryPO> list) {
|
||||
// list.forEach(item->{
|
||||
// try {
|
||||
// System.out.println(Thread.currentThread().getName() + ": processing data " + item.getNdid());
|
||||
// Thread.sleep(2000);
|
||||
// String version = csTopicService.getVersion(item.getNdid());
|
||||
// if (!Objects.isNull(version)){
|
||||
// csDeviceService.devAccessAskTemplate(item.getNdid(),version,1);
|
||||
// redisUtil.saveByKey(AppRedisKey.DEVICE_MID + item.getNdid(),1);
|
||||
// }
|
||||
// } catch (InterruptedException e) {
|
||||
// throw new RuntimeException(e);
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
|
||||
// @Test
|
||||
// @After
|
||||
// public void test() {
|
||||
// String nDid = "00B78D016AB5";
|
||||
// String version = "V1";
|
||||
// try {
|
||||
// inputStream.close();
|
||||
// } catch (IOException e) {
|
||||
//// //装置没有心跳,则立马发起接入请求
|
||||
//// csDeviceService.devAccessAskTemplate(nDid,version,1);
|
||||
//// log.info("装置掉线3分钟发送接入请求");
|
||||
//// Integer status = csEquipmentDeliveryService.queryEquipmentBynDid(nDid).getRunStatus();
|
||||
//// if (Objects.equals(status,AccessEnum.ONLINE.getCode())){
|
||||
//// throw new BusinessException(CommonResponseEnum.SUCCESS);
|
||||
//// }
|
||||
//// //心跳断连立马发起接入失败后,1分钟再次发起请求,请求3次
|
||||
//// for (int i = 2; i < 5; i++) {
|
||||
//// //接入再次失败,则定时发起接入请求
|
||||
//// Thread.sleep(1000 * 6);
|
||||
//// csDeviceService.devAccessAskTemplate(nDid,version,i);
|
||||
//// status = csEquipmentDeliveryService.queryEquipmentBynDid(nDid).getRunStatus();
|
||||
//// if (Objects.equals(status,AccessEnum.ONLINE.getCode())){
|
||||
//// break;
|
||||
//// }
|
||||
//// log.info("装置定时1分钟发送接入请求,第" + i + "次尝试");
|
||||
//// }
|
||||
// Integer status = csEquipmentDeliveryService.queryEquipmentBynDid(nDid).getRunStatus();
|
||||
// if (!Objects.isNull(status) && Objects.equals(status,AccessEnum.OFFLINE.getCode())){
|
||||
// final int[] mid = {5};
|
||||
// runnableFuture = executor.scheduleAtFixedRate(() -> {
|
||||
// csDeviceService.devAccessAskTemplate(nDid,version, mid[0]);
|
||||
// Integer status2 = csEquipmentDeliveryService.queryEquipmentBynDid(nDid).getRunStatus();
|
||||
// if (Objects.equals(status2,AccessEnum.ONLINE.getCode())){
|
||||
// runnableFuture.cancel(false);
|
||||
// } else {
|
||||
// mid[0] = mid[0] + 1;
|
||||
// }
|
||||
// //记录日志
|
||||
// log.info("装置掉线,定时10分钟发送接入请求,装置为:" + nDid + ",请求的时间戳为:" + System.currentTimeMillis());
|
||||
// }, 1, 1, TimeUnit.SECONDS);
|
||||
// }
|
||||
// } catch (Exception e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
// }
|
||||
|
||||
|
||||
// @Test
|
||||
// @After
|
||||
// public void test2() {
|
||||
// String nDid = "00B78D016AB5";
|
||||
// String version = "V1";
|
||||
// try {
|
||||
// //装置没有心跳,则立马发起接入请求
|
||||
// csDeviceService.devAccessAskTemplate(nDid,version,1);
|
||||
// log.info("装置掉线3分钟发送接入请求");
|
||||
// Integer status = csEquipmentDeliveryService.queryEquipmentBynDid(nDid).getRunStatus();
|
||||
// if (Objects.equals(status,AccessEnum.ONLINE.getCode())){
|
||||
// throw new BusinessException(CommonResponseEnum.SUCCESS);
|
||||
// }
|
||||
// //心跳断连立马发起接入失败后,1分钟再次发起请求,请求3次
|
||||
// for (int i = 2; i < 5; i++) {
|
||||
// //接入再次失败,则定时发起接入请求
|
||||
// Thread.sleep(1000 * 6);
|
||||
// csDeviceService.devAccessAskTemplate(nDid,version,i);
|
||||
// status = csEquipmentDeliveryService.queryEquipmentBynDid(nDid).getRunStatus();
|
||||
// if (Objects.equals(status,AccessEnum.ONLINE.getCode())){
|
||||
// break;
|
||||
// }
|
||||
// log.info("装置定时1分钟发送接入请求,第" + i + "次尝试");
|
||||
// }
|
||||
// if (!Objects.isNull(status) && Objects.equals(status,AccessEnum.OFFLINE.getCode())){
|
||||
// final int[] mid = {5};
|
||||
// ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
|
||||
// runnableFuture = executor.scheduleAtFixedRate(() -> {
|
||||
// csDeviceService.devAccessAskTemplate(nDid,version, mid[0]);
|
||||
// Integer status2 = csEquipmentDeliveryService.queryEquipmentBynDid(nDid).getRunStatus();
|
||||
// if (Objects.equals(status2,AccessEnum.ONLINE.getCode())){
|
||||
// runnableFuture.cancel(true);
|
||||
// } else {
|
||||
// mid[0] = mid[0] + 1;
|
||||
// }
|
||||
// //记录日志
|
||||
// log.info("装置掉线,定时10分钟发送接入请求,装置为:" + nDid + ",请求的时间戳为:" + System.currentTimeMillis());
|
||||
// }, 1, 1, TimeUnit.SECONDS);
|
||||
// }
|
||||
// } catch (Exception e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// @Test
|
||||
// @After
|
||||
// public void testDeviceAccess() {
|
||||
// String nDid = "00B78D016AB5";
|
||||
// String version = "V1";
|
||||
// try {
|
||||
// // 初次接入请求
|
||||
// initiateDeviceAccess(nDid, version, 1);
|
||||
// // 检查设备状态
|
||||
// Integer status = checkDeviceStatus(nDid);
|
||||
// if (status != null && Objects.equals(status, AccessEnum.ONLINE.getCode())) {
|
||||
// throw new BusinessException(CommonResponseEnum.SUCCESS);
|
||||
// }
|
||||
// // 重试接入请求,最多尝试3次
|
||||
// attemptReconnect(nDid, version);
|
||||
// // 如果设备仍然离线,开始定时任务发起接入请求
|
||||
// if (status != null && Objects.equals(status, AccessEnum.OFFLINE.getCode())) {
|
||||
// startScheduledReconnection(nDid, version);
|
||||
// }
|
||||
// } catch (Exception e) {
|
||||
// log.error("Device access error", e);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// private static final String BROKER_URL = "tcp://192.168.1.27:1885";
|
||||
// private static final String CLIENT_ID = "JavaAsyncPublisher";
|
||||
// private static final int QOS = 1; // Quality of Service
|
||||
// private static final int NUM_DEVICES = 10;
|
||||
// private static final String TOPIC_PREFIX = "/Dev/Data/V1/";
|
||||
// private static final int DEV_NUMS = 20;
|
||||
//
|
||||
// @Test
|
||||
// public void test11() {
|
||||
// MqttClient client = null;
|
||||
// ExecutorService executor = Executors.newFixedThreadPool(NUM_DEVICES);
|
||||
//
|
||||
// try {
|
||||
// client = new MqttClient(BROKER_URL, CLIENT_ID);
|
||||
// MqttConnectOptions options = new MqttConnectOptions();
|
||||
// options.setCleanSession(true);
|
||||
// client.connect(options);
|
||||
//
|
||||
// client.setCallback(new MqttCallback() {
|
||||
// @Override
|
||||
// public void connectionLost(Throwable cause) {
|
||||
// // Handle connection loss
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// public void messageArrived(String topic, MqttMessage message) throws Exception {
|
||||
// // Handle incoming messages (not used in this example)
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// public void deliveryComplete(IMqttDeliveryToken token) {
|
||||
// // Handle delivery completion
|
||||
// System.out.println("Message delivery completed for token: " + token.isComplete());
|
||||
// }
|
||||
// });
|
||||
//
|
||||
// // Submit tasks to the executor service to send messages to each device
|
||||
// for (int i = 1; i <= DEV_NUMS; i++) {
|
||||
// final String deviceId = "00B78DA8000" + i;
|
||||
// MqttClient finalClient = client;
|
||||
// executor.submit(() -> {
|
||||
// try {
|
||||
// String topic = TOPIC_PREFIX + deviceId;
|
||||
// String payload = "Message for device " + deviceId;
|
||||
// MqttMessage message = new MqttMessage(payload.getBytes());
|
||||
// message.setQos(QOS);
|
||||
// finalClient.publish(topic, message);
|
||||
// System.out.println("Sent message to topic: " + topic + " Message: " + payload);
|
||||
// } catch (MqttException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
// } catch (MqttException e) {
|
||||
// e.printStackTrace();
|
||||
// } finally {
|
||||
// if (client != null && client.isConnected()) {
|
||||
// try {
|
||||
// client.disconnect();
|
||||
// } catch (MqttException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// private void initiateDeviceAccess(String nDid, String version, int attempt) {
|
||||
// csDeviceService.devAccessAskTemplate(nDid, version, attempt);
|
||||
// log.info("装置掉线3分钟发送接入请求");
|
||||
// }
|
||||
//
|
||||
// private Integer checkDeviceStatus(String nDid) {
|
||||
// return csEquipmentDeliveryService.queryEquipmentBynDid(nDid).getRunStatus();
|
||||
// }
|
||||
//
|
||||
// private void attemptReconnect(String nDid, String version) throws InterruptedException {
|
||||
// for (int i = 2; i < 5; i++) {
|
||||
// Thread.sleep(1000 * 6); // 每 6 秒重试一次
|
||||
// initiateDeviceAccess(nDid, version, i);
|
||||
//
|
||||
// Integer status = checkDeviceStatus(nDid);
|
||||
// if (status != null && Objects.equals(status, AccessEnum.ONLINE.getCode())) {
|
||||
// break;
|
||||
// }
|
||||
// log.info("装置定时1分钟发送接入请求,第" + i + "次尝试");
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// private void startScheduledReconnection(String nDid, String version) {
|
||||
// final int[] attemptCounter = {5};
|
||||
// ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
|
||||
//
|
||||
// Runnable reconnectTask = () -> {
|
||||
// initiateDeviceAccess(nDid, version, attemptCounter[0]);
|
||||
//
|
||||
// Integer status = checkDeviceStatus(nDid);
|
||||
// if (status != null && Objects.equals(status, AccessEnum.ONLINE.getCode())) {
|
||||
// executor.shutdown(); // 关闭调度器
|
||||
// } else {
|
||||
// attemptCounter[0]++;
|
||||
// }
|
||||
// log.info("装置掉线,定时10分钟发送接入请求,装置为:" + nDid
|
||||
// + ",请求的时间戳为:" + System.currentTimeMillis());
|
||||
// };
|
||||
//
|
||||
// executor.scheduleAtFixedRate(reconnectTask, 1, 1, TimeUnit.SECONDS);
|
||||
// }
|
||||
|
||||
// 要计算CRC32的数据
|
||||
String data = "Hello, World!";
|
||||
CRC32 crc32 = new CRC32();
|
||||
crc32.update(data.getBytes());
|
||||
long crc32Value = crc32.getValue();
|
||||
// 将CRC32校验值转换为16进制字符串
|
||||
String crc32Str = String.format("%08X", crc32Value);
|
||||
System.out.println("CRC32校验值为: " + crc32Str);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
191
iot-access/access-boot/src/test/java/com/njcn/Test.java
Normal file
191
iot-access/access-boot/src/test/java/com/njcn/Test.java
Normal file
File diff suppressed because one or more lines are too long
@@ -0,0 +1,61 @@
|
||||
package com.njcn;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import com.njcn.csdevice.pojo.po.CsEquipmentDeliveryPO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.SneakyThrows;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
@Component
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class TestXianCheng {
|
||||
|
||||
|
||||
private static final long AUTO_TIME = 120L;
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
|
||||
Runnable task = () -> {
|
||||
log.info("轮询定时任务执行中!");
|
||||
ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||
// 创建一个ExecutorService来处理这些任务
|
||||
List<Future<Void>> futures = new ArrayList<>();
|
||||
// 提交任务给线程池执行
|
||||
for (int i = 0; i < 10; i++) {
|
||||
int index = i;
|
||||
futures.add(executor.submit(new Callable<Void>() {
|
||||
@Override
|
||||
public Void call() {
|
||||
access();
|
||||
return null;
|
||||
}
|
||||
}));
|
||||
}
|
||||
// 等待所有任务完成
|
||||
for (Future<Void> future : futures) {
|
||||
try {
|
||||
future.get();
|
||||
} catch (InterruptedException | ExecutionException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
// 关闭ExecutorService
|
||||
executor.shutdown();
|
||||
};
|
||||
//第一次执行的时间为120s,然后每隔120s执行一次
|
||||
scheduler.scheduleAtFixedRate(task,0,1,TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
|
||||
public static void access() {
|
||||
System.out.println("123");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -14,6 +14,12 @@ public class BaseRealDataSet implements Serializable {
|
||||
@ApiModelProperty("用户ID")
|
||||
private String userId;
|
||||
|
||||
@ApiModelProperty("结果(仅超时使用)")
|
||||
private boolean result = true;
|
||||
|
||||
@ApiModelProperty("描述")
|
||||
private String content;
|
||||
|
||||
@ApiModelProperty("监测点id")
|
||||
private String lineId;
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package com.njcn.rt.service.impl;
|
||||
|
||||
import cn.hutool.core.collection.CollectionUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.alibaba.nacos.shaded.com.google.gson.Gson;
|
||||
import com.github.tocrhz.mqtt.publisher.MqttPublisher;
|
||||
import com.njcn.access.utils.ChannelObjectUtil;
|
||||
import com.njcn.access.utils.RedisSetUtil;
|
||||
import com.njcn.common.pojo.exception.BusinessException;
|
||||
import com.njcn.common.utils.PubUtils;
|
||||
import com.njcn.csdevice.api.CsLineFeignClient;
|
||||
@@ -21,6 +23,7 @@ import com.njcn.rt.pojo.dto.HarmRealDataSet;
|
||||
import com.njcn.rt.service.IRtService;
|
||||
import com.njcn.web.utils.FloatUtils;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
@@ -36,6 +39,7 @@ import java.util.stream.Collectors;
|
||||
/**
|
||||
* @author xy
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class RtServiceImpl implements IRtService {
|
||||
@@ -46,14 +50,14 @@ public class RtServiceImpl implements IRtService {
|
||||
private final RedisUtil redisUtil;
|
||||
private final ChannelObjectUtil channelObjectUtil;
|
||||
private final MqttPublisher publisher;
|
||||
private final RedisSetUtil redisSetUtil;
|
||||
|
||||
@Override
|
||||
public void analysis(AppAutoDataMessage appAutoDataMessage) {
|
||||
List<CsDataArray> dataArrayList;
|
||||
//监测点id
|
||||
String lineId = appAutoDataMessage.getId() + appAutoDataMessage.getMsg().getClDid();
|
||||
//用户Id
|
||||
String userId = redisUtil.getObjectByKey("rtDataUserId:"+lineId).toString();
|
||||
redisUtil.delete("cldRtDataOverTime:"+lineId);
|
||||
//获取监测点基础信息
|
||||
CsLinePO po = csLineFeignClient.getById(lineId).getData();
|
||||
//获取数据集 dataSet
|
||||
@@ -73,6 +77,8 @@ public class RtServiceImpl implements IRtService {
|
||||
//fixme 这边先根据数据集的名称来返回对应实体,这边感觉不太合适,后期有好方案再调整
|
||||
//基础数据
|
||||
if (dataSet.getName().contains("Ds$Pqd$Rt$Basic$")) {
|
||||
//用户Id
|
||||
String userId = redisUtil.getObjectByKey("rtDataUserId:"+lineId).toString();
|
||||
BaseRealDataSet baseRealDataSet = assembleData(dataArrayList,item,po.getConType());
|
||||
baseRealDataSet.setUserId(userId);
|
||||
baseRealDataSet.setLineId(lineId);
|
||||
@@ -82,16 +88,40 @@ public class RtServiceImpl implements IRtService {
|
||||
long timestamp = item.getDataTimeSec() - 8*3600;
|
||||
baseRealDataSet.setDataTime(getTime(timestamp));
|
||||
publisher.send("/Web/RealData/" + lineId, new Gson().toJson(baseRealDataSet), 1, false);
|
||||
} else if (dataSet.getName().contains("实时数据")) {
|
||||
//用户Id
|
||||
Object redisObject = redisUtil.getObjectByKey("rtDataUserId:"+lineId);
|
||||
if (ObjectUtil.isNotNull(redisObject)) {
|
||||
Set<String> userSet = redisSetUtil.convertToSet(redisObject);
|
||||
userSet.forEach(userId->{
|
||||
BaseRealDataSet baseRealDataSet = assembleData(dataArrayList,item,po.getConType());
|
||||
baseRealDataSet.setUserId(userId);
|
||||
baseRealDataSet.setLineId(lineId);
|
||||
baseRealDataSet.setPt(po.getPtRatio().floatValue());
|
||||
baseRealDataSet.setCt(po.getCtRatio().floatValue());
|
||||
baseRealDataSet.setDataLevel(dataSet.getDataLevel());
|
||||
long timestamp = item.getDataTimeSec();
|
||||
baseRealDataSet.setDataTime(getTime(timestamp));
|
||||
publisher.send("/Web/RealData/" + userId, new Gson().toJson(baseRealDataSet), 1, false);
|
||||
});
|
||||
}
|
||||
}
|
||||
//fixme 目前实时数据只有基础数据和谐波数据,后期拓展,这边需要再判断
|
||||
else {
|
||||
long timestamp;
|
||||
//用户Id
|
||||
String userId = redisUtil.getObjectByKey("rtDataUserId:"+lineId).toString();
|
||||
HarmRealDataSet harmRealDataSet = harmData(dataArrayList,item,dataSet.getDataLevel(),po.getCtRatio());
|
||||
harmRealDataSet.setUserId(userId);
|
||||
harmRealDataSet.setLineId(lineId);
|
||||
harmRealDataSet.setPt(po.getPtRatio().floatValue());
|
||||
harmRealDataSet.setCt(po.getCtRatio().floatValue());
|
||||
harmRealDataSet.setDataLevel(dataSet.getDataLevel());
|
||||
long timestamp = item.getDataTimeSec() - 8*3600;
|
||||
if (ObjectUtil.isNotNull(po.getLineNo())) {
|
||||
timestamp = item.getDataTimeSec();
|
||||
} else {
|
||||
timestamp = item.getDataTimeSec() - 8*3600;
|
||||
}
|
||||
harmRealDataSet.setDataTime(getTime(timestamp));
|
||||
publisher.send("/Web/RealData/" + lineId, new Gson().toJson(harmRealDataSet), 1, false);
|
||||
}
|
||||
@@ -298,6 +328,8 @@ public class RtServiceImpl implements IRtService {
|
||||
}
|
||||
} else if (Objects.equals(item.getHarmName(),"Pq_RmsFundU")) {
|
||||
harmRealDataSet.setData1(FloatUtils.get2Float(item.getData()));
|
||||
} else if (Objects.equals(item.getHarmName(),"Pq_ThdU")) {
|
||||
harmRealDataSet.setData1(FloatUtils.get2Float(item.getData()));
|
||||
} else {
|
||||
String numberStr = item.getHarmName().substring(item.getHarmName().lastIndexOf('_') + 1);
|
||||
String fieldName = "data" + numberStr;
|
||||
@@ -322,4 +354,26 @@ public class RtServiceImpl implements IRtService {
|
||||
return harmRealDataSet;
|
||||
}
|
||||
|
||||
private Set<String> convertObjectToSetSafe(Object obj) {
|
||||
if (obj == null) {
|
||||
return new HashSet<>();
|
||||
}
|
||||
if (obj instanceof Set) {
|
||||
// 类型安全的转换
|
||||
Set<?> rawSet = (Set<?>) obj;
|
||||
return rawSet.stream()
|
||||
.filter(Objects::nonNull)
|
||||
.map(Object::toString)
|
||||
.collect(Collectors.toSet());
|
||||
} else if (obj instanceof Collection) {
|
||||
return ((Collection<?>) obj).stream()
|
||||
.filter(Objects::nonNull)
|
||||
.map(Object::toString)
|
||||
.collect(Collectors.toSet());
|
||||
} else {
|
||||
log.warn("Redis中的对象类型不是Set或Collection: {}", obj.getClass().getName());
|
||||
return new HashSet<>();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -33,7 +33,6 @@ import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.*;
|
||||
@@ -85,7 +84,7 @@ public class StatServiceImpl implements IStatService {
|
||||
List<CsEquipmentDeliveryPO> poList = channelObjectUtil.objectToList(redisUtil.getObjectByKey(AppRedisKey.DEVICE_LIST),CsEquipmentDeliveryPO.class);
|
||||
CsEquipmentDeliveryPO po = poList.stream().filter(item->Objects.equals(item.getNdid(),appAutoDataMessage.getId())).findFirst().orElse(null);
|
||||
List<SysDicTreePO> dictTreeList = channelObjectUtil.objectToList(redisUtil.getObjectByKey(AppRedisKey.DICT_TREE),SysDicTreePO.class);
|
||||
String code = dictTreeList.stream().filter(item->Objects.equals(item.getId(),po.getDevType())).findFirst().orElse(null).getCode();
|
||||
String code = Objects.requireNonNull(dictTreeList.stream().filter(item -> Objects.equals(item.getId(), po.getDevType())).findFirst().orElse(null)).getCode();
|
||||
|
||||
//便携式设备
|
||||
if (Objects.equals(DicDataEnum.PORTABLE.getCode(),code)) {
|
||||
@@ -93,13 +92,20 @@ public class StatServiceImpl implements IStatService {
|
||||
}
|
||||
//直连设备
|
||||
else if (Objects.equals(DicDataEnum.CONNECT_DEV.getCode(),code)) {
|
||||
if (Objects.equals(appAutoDataMessage.getDid(),1)){lineId = new Gson().fromJson(String.valueOf(redisUtil.getObjectByKey(AppRedisKey.LINE_POSITION+appAutoDataMessage.getId())), Map.class).get("0").toString();
|
||||
} else if (Objects.equals(appAutoDataMessage.getDid(),2)){
|
||||
if (Objects.equals(appAutoDataMessage.getDid(),1)) {
|
||||
lineId = new Gson().fromJson(String.valueOf(redisUtil.getObjectByKey(AppRedisKey.LINE_POSITION+appAutoDataMessage.getId())), Map.class).get("0").toString();
|
||||
} else if (Objects.equals(appAutoDataMessage.getDid(),2)) {
|
||||
lineId = new Gson().fromJson(String.valueOf(redisUtil.getObjectByKey(AppRedisKey.LINE_POSITION+appAutoDataMessage.getId())), Map.class).get(appAutoDataMessage.getMsg().getClDid().toString()).toString();
|
||||
}
|
||||
}
|
||||
//云前置设备
|
||||
else if (Objects.equals(DicDataEnum.DEV_CLD.getCode(),code)) {
|
||||
lineId = appAutoDataMessage.getId() + appAutoDataMessage.getMsg().getClDid();
|
||||
|
||||
}
|
||||
|
||||
//获取当前设备信息
|
||||
if (CollectionUtil.isNotEmpty(list)){
|
||||
if (CollectionUtil.isNotEmpty(list)) {
|
||||
List<String> recordList = new ArrayList<>();
|
||||
for (AppAutoDataMessage.DataArray item : list) {
|
||||
switch (item.getDataAttr()) {
|
||||
@@ -122,7 +128,8 @@ public class StatServiceImpl implements IStatService {
|
||||
default:
|
||||
break;
|
||||
}
|
||||
String key = AppRedisKey.DEV_MODEL.concat(dataArrayParam.getId() + dataArrayParam.getDid() + dataArrayParam.getCldId() + dataArrayParam.getStatMethod() + dataArrayParam.getIdx());
|
||||
int clDid = Objects.equals(DicDataEnum.DEV_CLD.getCode(),code)?1:appAutoDataMessage.getMsg().getClDid();
|
||||
String key = AppRedisKey.DEV_MODEL.concat(dataArrayParam.getId() + dataArrayParam.getDid() + clDid + dataArrayParam.getStatMethod() + dataArrayParam.getIdx());
|
||||
Object object = redisUtil.getObjectByKey(key);
|
||||
List<CsDataArray> dataArrayList;
|
||||
if (Objects.isNull(object)){
|
||||
@@ -130,10 +137,11 @@ public class StatServiceImpl implements IStatService {
|
||||
} else {
|
||||
dataArrayList = objectToList(object);
|
||||
}
|
||||
List<String> result = assembleData(lineId,dataArrayList,item,appAutoDataMessage.getMsg().getClDid(),dataArrayParam.getStatMethod(),po.getProcess());
|
||||
List<String> result = assembleData(lineId,dataArrayList,item,appAutoDataMessage.getMsg().getClDid(),dataArrayParam.getStatMethod(),po.getProcess(),code);
|
||||
recordList.addAll(result);
|
||||
//获取时间
|
||||
time = Instant.ofEpochSecond(item.getDataTimeSec()-8*3600)
|
||||
long devTime = Objects.equals(DicDataEnum.DEV_CLD.getCode(),code)?item.getDataTimeSec():item.getDataTimeSec()-8*3600;
|
||||
time = Instant.ofEpochSecond(devTime)
|
||||
.atZone(ZoneId.systemDefault())
|
||||
.toLocalDateTime();
|
||||
}
|
||||
@@ -191,7 +199,7 @@ public class StatServiceImpl implements IStatService {
|
||||
/**
|
||||
* influxDB数据组装
|
||||
*/
|
||||
public List<String> assembleData(String lineId,List<CsDataArray> dataArrayList,AppAutoDataMessage.DataArray item,Integer clDid,String statMethod,Integer process) {
|
||||
public List<String> assembleData(String lineId,List<CsDataArray> dataArrayList,AppAutoDataMessage.DataArray item,Integer clDid,String statMethod,Integer process,String devType) {
|
||||
List<String> records = new ArrayList<String>();
|
||||
//解码
|
||||
List<Float> floats = PubUtils.byteArrayToFloatList(Base64.getDecoder().decode(item.getData()));
|
||||
@@ -212,10 +220,11 @@ public class StatServiceImpl implements IStatService {
|
||||
tags.put(InfluxDBTableConstant.CL_DID,clDid.toString());
|
||||
tags.put(InfluxDBTableConstant.PROCESS,process.toString());
|
||||
Map<String,Object> fields = new HashMap<>();
|
||||
fields.put(dataArrayList.get(i).getName(),floats.get(i));
|
||||
//这边特殊处理,如果数据为3.14159,则将数据置为null
|
||||
fields.put(dataArrayList.get(i).getName(),Objects.equals(floats.get(i),3.14159f) ? null:floats.get(i));
|
||||
fields.put(InfluxDBTableConstant.IS_ABNORMAL,item.getDataTag());
|
||||
//fixme 这边前置传递的应该是UTC时间,但是前置说是传递的北京时间,讨论了一下没太理解。这边暂时先这样处理,influx入库处理成北京时间,减去8小时。
|
||||
Point point = influxDbUtils.pointBuilder(tableName, item.getDataTimeSec()-8*3600, TimeUnit.SECONDS, tags, fields);
|
||||
Point point = influxDbUtils.pointBuilder(tableName, Objects.equals(DicDataEnum.DEV_CLD.getCode(),devType)?item.getDataTimeSec():item.getDataTimeSec()-8*3600, TimeUnit.SECONDS, tags, fields);
|
||||
BatchPoints batchPoints = BatchPoints.database(influxDbUtils.getDbName()).retentionPolicy("").consistency(InfluxDB.ConsistencyLevel.ALL).build();
|
||||
batchPoints.point(point);
|
||||
records.add(batchPoints.lineProtocol());
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.njcn.zlevent.api;
|
||||
import com.njcn.common.pojo.constant.ServerInfo;
|
||||
import com.njcn.common.pojo.response.HttpResult;
|
||||
import com.njcn.mq.message.AppEventMessage;
|
||||
import com.njcn.mq.message.CldLogMessage;
|
||||
import com.njcn.zlevent.api.fallback.EventClientFallbackFactory;
|
||||
import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
@@ -20,4 +21,7 @@ public interface EventFeignClient {
|
||||
@PostMapping("/portableData")
|
||||
HttpResult<String> getPortableData(@RequestBody AppEventMessage appEventMessage);
|
||||
|
||||
@PostMapping("/cldEventData")
|
||||
HttpResult<String> getCldEventData(@RequestBody CldLogMessage cldLogMessage);
|
||||
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import com.njcn.common.pojo.enums.response.CommonResponseEnum;
|
||||
import com.njcn.common.pojo.exception.BusinessException;
|
||||
import com.njcn.common.pojo.response.HttpResult;
|
||||
import com.njcn.mq.message.AppEventMessage;
|
||||
import com.njcn.mq.message.CldLogMessage;
|
||||
import com.njcn.zlevent.api.EventFeignClient;
|
||||
import feign.hystrix.FallbackFactory;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -37,6 +38,12 @@ public class EventClientFallbackFactory implements FallbackFactory<EventFeignCli
|
||||
throw new BusinessException(finalExceptionEnum);
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpResult<String> getCldEventData(CldLogMessage cldLogMessage) {
|
||||
log.error("{}异常,降级处理,异常为:{}","云前置事件处理",cause.toString());
|
||||
throw new BusinessException(finalExceptionEnum);
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.njcn.common.pojo.enums.response.CommonResponseEnum;
|
||||
import com.njcn.common.pojo.response.HttpResult;
|
||||
import com.njcn.common.utils.HttpResultUtil;
|
||||
import com.njcn.mq.message.AppEventMessage;
|
||||
import com.njcn.mq.message.CldLogMessage;
|
||||
import com.njcn.web.controller.BaseController;
|
||||
import com.njcn.zlevent.service.IEventService;
|
||||
import io.swagger.annotations.Api;
|
||||
@@ -54,4 +55,14 @@ public class EventController extends BaseController {
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||
}
|
||||
|
||||
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
|
||||
@PostMapping("/cldEventData")
|
||||
@ApiOperation("云前置事件处理")
|
||||
@ApiImplicitParam(name = "cldLogMessage", value = "数据实体", required = true)
|
||||
public HttpResult<String> getCldEventData(@RequestBody CldLogMessage cldLogMessage){
|
||||
String methodDescribe = getMethodDescribe("getCldEventData");
|
||||
eventService.getCldEventData(cldLogMessage);
|
||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.njcn.zlevent.service;
|
||||
|
||||
import com.njcn.mq.message.AppEventMessage;
|
||||
import com.njcn.mq.message.CldLogMessage;
|
||||
|
||||
/**
|
||||
* @author xy
|
||||
@@ -25,4 +26,11 @@ public interface IEventService {
|
||||
*/
|
||||
void getPortableData(AppEventMessage appEventMessage);
|
||||
|
||||
/**
|
||||
* 云前置设备基础数据
|
||||
* 1.装置发起数据记录开始动作,库中新增数据;
|
||||
* @param cldLogMessage
|
||||
*/
|
||||
void getCldEventData( CldLogMessage cldLogMessage);
|
||||
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.njcn.zlevent.service.impl;
|
||||
import cn.hutool.core.collection.CollectionUtil;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import com.alibaba.nacos.shaded.com.google.gson.Gson;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.njcn.common.pojo.exception.BusinessException;
|
||||
import com.njcn.csdevice.api.CsLineFeignClient;
|
||||
import com.njcn.csdevice.api.EquipmentFeignClient;
|
||||
@@ -16,6 +17,7 @@ import com.njcn.csharmonic.pojo.po.CsEventPO;
|
||||
import com.njcn.influx.pojo.constant.InfluxDBTableConstant;
|
||||
import com.njcn.influx.utils.InfluxDbUtils;
|
||||
import com.njcn.mq.message.AppEventMessage;
|
||||
import com.njcn.mq.message.CldLogMessage;
|
||||
import com.njcn.redis.pojo.enums.AppRedisKey;
|
||||
import com.njcn.redis.utils.RedisUtil;
|
||||
import com.njcn.stat.enums.StatResponseEnum;
|
||||
@@ -92,7 +94,6 @@ public class EventServiceImpl implements IEventService {
|
||||
//获取设备类型 true:治理设备 false:其他类型的设备
|
||||
boolean devModel = equipmentFeignClient.judgeDevModel(appEventMessage.getId()).getData();
|
||||
try {
|
||||
// lineId = appEventMessage.getId() + appEventMessage.getMsg().getClDid();
|
||||
if (devModel) {
|
||||
if (Objects.equals(appEventMessage.getDid(),1)){
|
||||
lineId = new Gson().fromJson(String.valueOf(redisUtil.getObjectByKey(AppRedisKey.LINE_POSITION+appEventMessage.getId())), Map.class).get("0").toString();
|
||||
@@ -103,74 +104,81 @@ public class EventServiceImpl implements IEventService {
|
||||
lineId = new Gson().fromJson(String.valueOf(redisUtil.getObjectByKey(AppRedisKey.LINE_POSITION+appEventMessage.getId())), Map.class).get(appEventMessage.getMsg().getClDid().toString()).toString();
|
||||
}
|
||||
|
||||
|
||||
|
||||
//处理事件数据
|
||||
List<AppEventMessage.DataArray> dataArray = appEventMessage.getMsg().getDataArray();
|
||||
for (AppEventMessage.DataArray item : dataArray) {
|
||||
eventTime = timeFormat(item.getDataTimeSec(),item.getDataTimeUSec());
|
||||
id = IdUtil.fastSimpleUUID();
|
||||
//事件入库
|
||||
CsEventPO csEvent = new CsEventPO();
|
||||
csEvent.setId(id);
|
||||
csEvent.setDeviceId(po.getId());
|
||||
csEvent.setProcess(po.getProcess());
|
||||
csEvent.setCode(item.getCode());
|
||||
eventTime = timeFormat(item.getDataTimeSec(),item.getDataTimeUSec());
|
||||
csEvent.setStartTime(eventTime);
|
||||
tag = item.getName();
|
||||
csEvent.setTag(tag);
|
||||
if (Objects.equals(item.getType(),"2")){
|
||||
csEvent.setType(0);
|
||||
} else if (Objects.equals(item.getType(),"3")){
|
||||
csEvent.setType(1);
|
||||
} else if (Objects.equals(item.getType(),"1")){
|
||||
csEvent.setType(2);
|
||||
}
|
||||
csEvent.setLevel(Integer.parseInt(item.getType()));
|
||||
csEvent.setClDid(appEventMessage.getMsg().getClDid());
|
||||
csEvent.setLineId(lineId);
|
||||
//参数入库
|
||||
Map<String,String> map = new Gson().fromJson(String.valueOf(redisUtil.getObjectByKey(AppRedisKey.ELE_EPD_PQD)), Map.class);
|
||||
//判断是否有参数
|
||||
List<AppEventMessage.Param> params = item.getParam();
|
||||
if (CollectionUtil.isNotEmpty(params)) {
|
||||
String tableName = map.get(item.getName());
|
||||
Map<String, String> tags = new HashMap<>();
|
||||
tags.put(InfluxDBTableConstant.UUID,id);
|
||||
Map<String,Object> fields = new HashMap<>();
|
||||
for (AppEventMessage.Param param : params) {
|
||||
if (Objects.equals(param.getName(),ZlConstant.EVT_PARAM_TM)){
|
||||
csEvent.setPersistTime(Double.parseDouble(param.getData().toString()));
|
||||
}
|
||||
fields.put(param.getName(),param.getData());
|
||||
//判断事件是否存在,如果存在则不处理
|
||||
LambdaQueryWrapper<CsEventPO> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.eq(CsEventPO::getDeviceId,po.getId())
|
||||
.eq(CsEventPO::getTag,tag)
|
||||
.eq(CsEventPO::getStartTime,eventTime)
|
||||
.eq(CsEventPO::getLineId,lineId);
|
||||
List<CsEventPO> eventList = csEventService.list(queryWrapper);
|
||||
if (CollectionUtil.isEmpty(eventList)) {
|
||||
id = IdUtil.fastSimpleUUID();
|
||||
//事件入库
|
||||
CsEventPO csEvent = new CsEventPO();
|
||||
csEvent.setId(id);
|
||||
csEvent.setDeviceId(po.getId());
|
||||
csEvent.setProcess(po.getProcess());
|
||||
csEvent.setCode(item.getCode());
|
||||
eventTime = timeFormat(item.getDataTimeSec(),item.getDataTimeUSec());
|
||||
csEvent.setStartTime(eventTime);
|
||||
tag = item.getName();
|
||||
csEvent.setTag(tag);
|
||||
if (Objects.equals(item.getType(),"2")){
|
||||
csEvent.setType(0);
|
||||
} else if (Objects.equals(item.getType(),"3")){
|
||||
csEvent.setType(1);
|
||||
} else if (Objects.equals(item.getType(),"1")){
|
||||
csEvent.setType(2);
|
||||
}
|
||||
//只有治理型号的设备有监测位置
|
||||
if (devModel) {
|
||||
if (appEventMessage.getMsg().getClDid() == 1) {
|
||||
fields.put("Evt_Param_Position","电网侧");
|
||||
csEvent.setLocation("grid");
|
||||
} else if (appEventMessage.getMsg().getClDid() == 2) {
|
||||
fields.put("Evt_Param_Position","负载侧");
|
||||
csEvent.setLocation("load");
|
||||
csEvent.setLevel(Integer.parseInt(item.getType()));
|
||||
csEvent.setClDid(appEventMessage.getMsg().getClDid());
|
||||
csEvent.setLineId(lineId);
|
||||
//参数入库
|
||||
Map<String,String> map = new Gson().fromJson(String.valueOf(redisUtil.getObjectByKey(AppRedisKey.ELE_EPD_PQD)), Map.class);
|
||||
//判断是否有参数
|
||||
List<AppEventMessage.Param> params = item.getParam();
|
||||
if (CollectionUtil.isNotEmpty(params)) {
|
||||
String tableName = map.get(item.getName());
|
||||
Map<String, String> tags = new HashMap<>();
|
||||
tags.put(InfluxDBTableConstant.UUID,id);
|
||||
Map<String,Object> fields = new HashMap<>();
|
||||
for (AppEventMessage.Param param : params) {
|
||||
if (Objects.equals(param.getName(),ZlConstant.EVT_PARAM_TM)){
|
||||
csEvent.setPersistTime(Double.parseDouble(param.getData().toString()));
|
||||
}
|
||||
fields.put(param.getName(),param.getData());
|
||||
}
|
||||
//只有治理型号的设备有监测位置
|
||||
if (devModel) {
|
||||
if (appEventMessage.getMsg().getClDid() == 1) {
|
||||
fields.put("Evt_Param_Position","电网侧");
|
||||
csEvent.setLocation("grid");
|
||||
} else if (appEventMessage.getMsg().getClDid() == 2) {
|
||||
fields.put("Evt_Param_Position","负载侧");
|
||||
csEvent.setLocation("load");
|
||||
}
|
||||
}
|
||||
//fixme 这边前置传递的应该是UTC时间,但是前置说是传递的北京时间,讨论了一下没太理解。这边暂时先这样处理,influx入库处理成北京时间,减去8小时。
|
||||
Point point = influxDbUtils.pointBuilder(tableName, item.getDataTimeSec()-8*3600, TimeUnit.SECONDS, tags, fields);
|
||||
BatchPoints batchPoints = BatchPoints.database(influxDbUtils.getDbName()).retentionPolicy("").consistency(InfluxDB.ConsistencyLevel.ALL).build();
|
||||
batchPoints.point(point);
|
||||
records.add(batchPoints.lineProtocol());
|
||||
}
|
||||
//fixme 这边前置传递的应该是UTC时间,但是前置说是传递的北京时间,讨论了一下没太理解。这边暂时先这样处理,influx入库处理成北京时间,减去8小时。
|
||||
Point point = influxDbUtils.pointBuilder(tableName, item.getDataTimeSec()-8*3600, TimeUnit.SECONDS, tags, fields);
|
||||
BatchPoints batchPoints = BatchPoints.database(influxDbUtils.getDbName()).retentionPolicy("").consistency(InfluxDB.ConsistencyLevel.ALL).build();
|
||||
batchPoints.point(point);
|
||||
records.add(batchPoints.lineProtocol());
|
||||
list1.add(csEvent);
|
||||
//事件处理日志库
|
||||
CsEventLogs csEventLogs = new CsEventLogs();
|
||||
csEventLogs.setLineId(lineId);
|
||||
csEventLogs.setDeviceId(po.getId());
|
||||
csEventLogs.setStartTime(timeFormat(item.getDataTimeSec(),item.getDataTimeUSec()));
|
||||
csEventLogs.setTag(item.getName());
|
||||
csEventLogs.setStatus(1);
|
||||
csEventLogs.setTime(LocalDateTime.now());
|
||||
csEventLogsService.save(csEventLogs);
|
||||
}
|
||||
list1.add(csEvent);
|
||||
//事件处理日志库
|
||||
CsEventLogs csEventLogs = new CsEventLogs();
|
||||
csEventLogs.setLineId(lineId);
|
||||
csEventLogs.setDeviceId(po.getId());
|
||||
csEventLogs.setStartTime(timeFormat(item.getDataTimeSec(),item.getDataTimeUSec()));
|
||||
csEventLogs.setTag(item.getName());
|
||||
csEventLogs.setStatus(1);
|
||||
csEventLogs.setTime(LocalDateTime.now());
|
||||
csEventLogsService.save(csEventLogs);
|
||||
}
|
||||
//cs_event入库
|
||||
if (CollectionUtil.isNotEmpty(list1)){
|
||||
@@ -251,6 +259,36 @@ public class EventServiceImpl implements IEventService {
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void getCldEventData(CldLogMessage cldLogMessage) {
|
||||
CsEventPO po = new CsEventPO();
|
||||
po.setStartTime(LocalDateTime.parse(cldLogMessage.getTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
|
||||
po.setTag(cldLogMessage.getLog());
|
||||
po.setClDid(1);
|
||||
po.setLevel(3);
|
||||
po.setProcess(4);
|
||||
po.setCode(cldLogMessage.getCode());
|
||||
//前置告警
|
||||
if (Objects.equals(cldLogMessage.getLevel(),"process")) {
|
||||
//这边将前置服务器id当作设备id
|
||||
po.setDeviceId(cldLogMessage.getNodeId());
|
||||
po.setClDid(Integer.valueOf(cldLogMessage.getProcessNo()));
|
||||
po.setType(4);
|
||||
}
|
||||
//设备和监测点告警
|
||||
else {
|
||||
if (Objects.equals(cldLogMessage.getLevel(),"terminal")) {
|
||||
po.setDeviceId(cldLogMessage.getBusinessId());
|
||||
} else {
|
||||
CsLinePO line = csLineFeignClient.getById(cldLogMessage.getBusinessId()).getData();
|
||||
po.setDeviceId(line.getDeviceId());
|
||||
po.setLineId(cldLogMessage.getBusinessId());
|
||||
}
|
||||
po.setType(3);
|
||||
}
|
||||
csEventService.save(po);
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理电压
|
||||
* @param vol
|
||||
|
||||
@@ -2,6 +2,10 @@ package com.njcn;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.nacos.shaded.com.google.gson.Gson;
|
||||
import com.github.tocrhz.mqtt.publisher.MqttPublisher;
|
||||
import com.njcn.access.enums.AccessEnum;
|
||||
import com.njcn.access.enums.TypeEnum;
|
||||
import com.njcn.access.pojo.dto.ReqAndResDto;
|
||||
import com.njcn.csharmonic.api.WavePicFeignClient;
|
||||
import com.njcn.influx.pojo.constant.InfluxDBTableConstant;
|
||||
import com.njcn.influx.utils.InfluxDbUtils;
|
||||
@@ -15,6 +19,8 @@ import com.njcn.zlevent.ZlEventBootApplication;
|
||||
import com.njcn.zlevent.pojo.constant.ZlConstant;
|
||||
import com.njcn.zlevent.pojo.dto.FileStreamDto;
|
||||
import com.njcn.zlevent.pojo.dto.WaveTimeDto;
|
||||
import com.njcn.zlevent.service.ICsWaveService;
|
||||
import net.sf.json.JSONObject;
|
||||
import org.influxdb.InfluxDB;
|
||||
import org.influxdb.dto.BatchPoints;
|
||||
import org.influxdb.dto.Point;
|
||||
@@ -59,6 +65,11 @@ public class AppTest {
|
||||
@Resource
|
||||
private InfluxDbUtils influxDbUtils;
|
||||
|
||||
@Resource
|
||||
private MqttPublisher publisher;
|
||||
@Resource
|
||||
private ICsWaveService csWaveService;
|
||||
|
||||
/**
|
||||
* Rigorous Test :-)
|
||||
*/
|
||||
@@ -68,6 +79,39 @@ public class AppTest {
|
||||
assertTrue( true );
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test00() {
|
||||
long time = 1726237055L;
|
||||
long subtleTime = 889000L;
|
||||
Double millisecond = 1430.0;
|
||||
|
||||
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
time = time - 8*3600;
|
||||
// 将millisecond转换为长整型,并乘以1000以获取微秒
|
||||
long millisecondValue = millisecond.longValue() * 1000;
|
||||
long time1 = time * 1000000 + subtleTime;
|
||||
long time2 = time * 1000000 + subtleTime + millisecondValue;
|
||||
String time1String = String.valueOf(time1);
|
||||
String time2String = String.valueOf(time2);
|
||||
|
||||
String time11 = time1String.substring(time1String.length() - 6);
|
||||
String time111 = time1String.substring(0,time1String.length() - 6);
|
||||
String formatTime1 = format.format(Long.parseLong(time111) * 1000);
|
||||
|
||||
String time22 = time2String.substring(time2String.length() - 6);
|
||||
String time222 = time2String.substring(0,time2String.length() - 6);
|
||||
String formatTime2 = format.format(Long.parseLong(time222) * 1000);
|
||||
System.out.println(formatTime1 + "." + time11);
|
||||
System.out.println(formatTime2 + "." + time22);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test11() {
|
||||
String fileName = "/bd0/comtrade/PQS_PQM1_000063_20241029_101442_886";
|
||||
boolean result = csWaveService.findCountByName(fileName);
|
||||
System.out.println("result==:" + result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test3() {
|
||||
List<String> records = new ArrayList<String>();
|
||||
|
||||
@@ -81,6 +81,17 @@
|
||||
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
|
||||
<version>3.5.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.njcn</groupId>
|
||||
<artifactId>cs-device-api</artifactId>
|
||||
<version>${project.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>com.njcn</groupId>
|
||||
<artifactId>common-device-biz</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
@@ -15,7 +15,6 @@ import org.springframework.context.annotation.DependsOn;
|
||||
@Slf4j
|
||||
@EnableFeignClients(basePackages = "com.njcn")
|
||||
@SpringBootApplication(scanBasePackages = "com.njcn")
|
||||
@DependsOn("proxyMapperRegister")
|
||||
public class MessageBootApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
package com.njcn.message.consumer;
|
||||
|
||||
import com.njcn.csdevice.api.EquipmentFeignClient;
|
||||
import com.njcn.middle.rocket.constant.EnhanceMessageConstant;
|
||||
import com.njcn.middle.rocket.handler.EnhanceConsumerMessageHandler;
|
||||
import com.njcn.mq.constant.BusinessTopic;
|
||||
import com.njcn.mq.constant.MessageStatus;
|
||||
import com.njcn.mq.message.CldDeviceRunFlagMessage;
|
||||
import com.njcn.redis.pojo.enums.AppRedisKey;
|
||||
import com.njcn.redis.pojo.enums.RedisKeyEnum;
|
||||
import com.njcn.redis.utils.RedisUtil;
|
||||
import com.njcn.system.api.RocketMqLogFeignClient;
|
||||
import com.njcn.system.pojo.po.RocketmqMsgErrorLog;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
|
||||
import org.apache.rocketmq.spring.core.RocketMQListener;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* 类的介绍:云前置状态反转
|
||||
*
|
||||
* @author xuyang
|
||||
* @version 1.0.0
|
||||
* @createTime 2025/9/16
|
||||
*/
|
||||
@Service
|
||||
@RocketMQMessageListener(
|
||||
topic = BusinessTopic.DEVICE_RUN_FLAG_TOPIC,
|
||||
consumerGroup = BusinessTopic.DEVICE_RUN_FLAG_TOPIC,
|
||||
consumeThreadNumber = 10,
|
||||
enableMsgTrace = true
|
||||
)
|
||||
@Slf4j
|
||||
public class CldDevRunFlagConsumer extends EnhanceConsumerMessageHandler<CldDeviceRunFlagMessage> implements RocketMQListener<CldDeviceRunFlagMessage> {
|
||||
|
||||
@Resource
|
||||
private RedisUtil redisUtil;
|
||||
@Resource
|
||||
private RocketMqLogFeignClient rocketMqLogFeignClient;
|
||||
@Resource
|
||||
private EquipmentFeignClient equipmentFeignClient;
|
||||
|
||||
@Override
|
||||
protected void handleMessage(CldDeviceRunFlagMessage cldDeviceRunFlagMessage) {
|
||||
log.info("分发至翻转设备状态");
|
||||
int status = Objects.equals(cldDeviceRunFlagMessage.getStatus(),"0") ? 1 : 2;
|
||||
equipmentFeignClient.flipCldDevStatus(cldDeviceRunFlagMessage.getId(), status);
|
||||
}
|
||||
|
||||
|
||||
/***
|
||||
* 通过redis分布式锁判断当前消息所处状态
|
||||
* 1、null 查不到该key的数据,属于第一次消费,放行
|
||||
* 2、fail 上次消息消费时发生异常,放行
|
||||
* 3、being processed 正在处理,打回去
|
||||
* 4、success 最近72小时消费成功,避免重复消费,打回去
|
||||
*/
|
||||
@Override
|
||||
public boolean filter(CldDeviceRunFlagMessage message) {
|
||||
String keyStatus = redisUtil.getStringByKey(AppRedisKey.RMQ_CONSUME_KEY.concat(message.getKey()));
|
||||
if (Objects.isNull(keyStatus) || keyStatus.equalsIgnoreCase(MessageStatus.FAIL)) {
|
||||
redisUtil.saveByKeyWithExpire(AppRedisKey.RMQ_CONSUME_KEY.concat(message.getKey()), MessageStatus.BEING_PROCESSED, 60L);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 消费成功,缓存到redis72小时,避免重复消费
|
||||
*/
|
||||
@Override
|
||||
protected void consumeSuccess(CldDeviceRunFlagMessage message) {
|
||||
redisUtil.saveByKeyWithExpire(AppRedisKey.RMQ_CONSUME_KEY.concat(message.getKey()), MessageStatus.SUCCESS, RedisKeyEnum.ROCKET_MQ_KEY.getTime());
|
||||
}
|
||||
|
||||
/**
|
||||
* 发生异常时,进行错误信息入库保存
|
||||
* 默认没有实现类,子类可以实现该方法,调用feign接口进行入库保存
|
||||
*/
|
||||
@Override
|
||||
protected void saveExceptionMsgLog(CldDeviceRunFlagMessage message, String identity, Exception exception) {
|
||||
redisUtil.saveByKeyWithExpire(AppRedisKey.RMQ_CONSUME_KEY.concat(message.getKey()), MessageStatus.FAIL, RedisKeyEnum.ROCKET_MQ_KEY.getTime());
|
||||
RocketmqMsgErrorLog rocketmqMsgErrorLog = new RocketmqMsgErrorLog();
|
||||
rocketmqMsgErrorLog.setMsgKey(message.getKey());
|
||||
rocketmqMsgErrorLog.setResource(message.getSource());
|
||||
if (identity.equalsIgnoreCase(EnhanceMessageConstant.IDENTITY_SINGLE)) {
|
||||
//数据库字段配置长度200,避免插入失败,大致分析异常原因
|
||||
String exceptionMsg = exception.getMessage();
|
||||
if(exceptionMsg.length() > 200){
|
||||
exceptionMsg = exceptionMsg.substring(0,180);
|
||||
}
|
||||
rocketmqMsgErrorLog.setRecord(exceptionMsg);
|
||||
//如果是当前消息重试的则略过
|
||||
if(!message.getSource().startsWith(EnhanceMessageConstant.RETRY_PREFIX)){
|
||||
//单次消费异常
|
||||
rocketMqLogFeignClient.add(rocketmqMsgErrorLog);
|
||||
}
|
||||
} else {
|
||||
rocketmqMsgErrorLog.setRecord("重试消费" + super.getMaxRetryTimes() + "次,依旧消费失败。");
|
||||
//重试N次后,依然消费异常
|
||||
rocketMqLogFeignClient.add(rocketmqMsgErrorLog);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/***
|
||||
* 处理失败后,是否重试
|
||||
* 一般开启
|
||||
*/
|
||||
@Override
|
||||
protected boolean isRetry() {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/***
|
||||
* 消费失败是否抛出异常,抛出异常后就不再消费了
|
||||
*/
|
||||
@Override
|
||||
protected boolean throwException() {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/***
|
||||
* 调用父类handler处理消息的元信息
|
||||
*/
|
||||
@Override
|
||||
public void onMessage(CldDeviceRunFlagMessage appAutoDataMessage) {
|
||||
super.dispatchMessage(appAutoDataMessage);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package com.njcn.message.consumer;
|
||||
|
||||
import com.njcn.middle.rocket.constant.EnhanceMessageConstant;
|
||||
import com.njcn.middle.rocket.handler.EnhanceConsumerMessageHandler;
|
||||
import com.njcn.mq.constant.BusinessTopic;
|
||||
import com.njcn.mq.constant.MessageStatus;
|
||||
import com.njcn.mq.message.CldLogMessage;
|
||||
import com.njcn.redis.pojo.enums.AppRedisKey;
|
||||
import com.njcn.redis.pojo.enums.RedisKeyEnum;
|
||||
import com.njcn.redis.utils.RedisUtil;
|
||||
import com.njcn.system.api.RocketMqLogFeignClient;
|
||||
import com.njcn.system.pojo.po.RocketmqMsgErrorLog;
|
||||
import com.njcn.zlevent.api.EventFeignClient;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
|
||||
import org.apache.rocketmq.spring.core.RocketMQListener;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* 类的介绍: 云前置心跳消息
|
||||
*
|
||||
* @author xuyang
|
||||
* @version 1.0.0
|
||||
* @createTime 2025/9/16
|
||||
*/
|
||||
@Service
|
||||
@RocketMQMessageListener(
|
||||
topic = BusinessTopic.LOG_TOPIC,
|
||||
consumerGroup = BusinessTopic.LOG_TOPIC,
|
||||
consumeThreadNumber = 10,
|
||||
enableMsgTrace = true
|
||||
)
|
||||
@Slf4j
|
||||
public class CldEventConsumer extends EnhanceConsumerMessageHandler<CldLogMessage> implements RocketMQListener<CldLogMessage> {
|
||||
|
||||
@Resource
|
||||
private RedisUtil redisUtil;
|
||||
@Resource
|
||||
private RocketMqLogFeignClient rocketMqLogFeignClient;
|
||||
@Resource
|
||||
private EventFeignClient eventFeignClient;
|
||||
|
||||
@Override
|
||||
protected void handleMessage(CldLogMessage cldLogMessage) {
|
||||
log.info("分发至云前置告警事件处理");
|
||||
eventFeignClient.getCldEventData(cldLogMessage);
|
||||
}
|
||||
|
||||
|
||||
/***
|
||||
* 通过redis分布式锁判断当前消息所处状态
|
||||
* 1、null 查不到该key的数据,属于第一次消费,放行
|
||||
* 2、fail 上次消息消费时发生异常,放行
|
||||
* 3、being processed 正在处理,打回去
|
||||
* 4、success 最近72小时消费成功,避免重复消费,打回去
|
||||
*/
|
||||
@Override
|
||||
public boolean filter(CldLogMessage message) {
|
||||
String keyStatus = redisUtil.getStringByKey(AppRedisKey.RMQ_CONSUME_KEY.concat(message.getKey()));
|
||||
if (Objects.isNull(keyStatus) || keyStatus.equalsIgnoreCase(MessageStatus.FAIL)) {
|
||||
redisUtil.saveByKeyWithExpire(AppRedisKey.RMQ_CONSUME_KEY.concat(message.getKey()), MessageStatus.BEING_PROCESSED, 60L);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 消费成功,缓存到redis72小时,避免重复消费
|
||||
*/
|
||||
@Override
|
||||
protected void consumeSuccess(CldLogMessage message) {
|
||||
redisUtil.saveByKeyWithExpire(AppRedisKey.RMQ_CONSUME_KEY.concat(message.getKey()), MessageStatus.SUCCESS, RedisKeyEnum.ROCKET_MQ_KEY.getTime());
|
||||
}
|
||||
|
||||
/**
|
||||
* 发生异常时,进行错误信息入库保存
|
||||
* 默认没有实现类,子类可以实现该方法,调用feign接口进行入库保存
|
||||
*/
|
||||
@Override
|
||||
protected void saveExceptionMsgLog(CldLogMessage message, String identity, Exception exception) {
|
||||
redisUtil.saveByKeyWithExpire(AppRedisKey.RMQ_CONSUME_KEY.concat(message.getKey()), MessageStatus.FAIL, RedisKeyEnum.ROCKET_MQ_KEY.getTime());
|
||||
RocketmqMsgErrorLog rocketmqMsgErrorLog = new RocketmqMsgErrorLog();
|
||||
rocketmqMsgErrorLog.setMsgKey(message.getKey());
|
||||
rocketmqMsgErrorLog.setResource(message.getSource());
|
||||
if (identity.equalsIgnoreCase(EnhanceMessageConstant.IDENTITY_SINGLE)) {
|
||||
//数据库字段配置长度200,避免插入失败,大致分析异常原因
|
||||
String exceptionMsg = exception.getMessage();
|
||||
if(exceptionMsg.length() > 200){
|
||||
exceptionMsg = exceptionMsg.substring(0,180);
|
||||
}
|
||||
rocketmqMsgErrorLog.setRecord(exceptionMsg);
|
||||
//如果是当前消息重试的则略过
|
||||
if(!message.getSource().startsWith(EnhanceMessageConstant.RETRY_PREFIX)){
|
||||
//单次消费异常
|
||||
rocketMqLogFeignClient.add(rocketmqMsgErrorLog);
|
||||
}
|
||||
} else {
|
||||
rocketmqMsgErrorLog.setRecord("重试消费" + super.getMaxRetryTimes() + "次,依旧消费失败。");
|
||||
//重试N次后,依然消费异常
|
||||
rocketMqLogFeignClient.add(rocketmqMsgErrorLog);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/***
|
||||
* 处理失败后,是否重试
|
||||
* 一般开启
|
||||
*/
|
||||
@Override
|
||||
protected boolean isRetry() {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/***
|
||||
* 消费失败是否抛出异常,抛出异常后就不再消费了
|
||||
*/
|
||||
@Override
|
||||
protected boolean throwException() {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/***
|
||||
* 调用父类handler处理消息的元信息
|
||||
*/
|
||||
@Override
|
||||
public void onMessage(CldLogMessage cldLogMessage) {
|
||||
super.dispatchMessage(cldLogMessage);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package com.njcn.message.consumer;
|
||||
|
||||
import com.njcn.middle.rocket.constant.EnhanceMessageConstant;
|
||||
import com.njcn.middle.rocket.handler.EnhanceConsumerMessageHandler;
|
||||
import com.njcn.mq.constant.BusinessTopic;
|
||||
import com.njcn.mq.constant.MessageStatus;
|
||||
import com.njcn.mq.message.CldHeartBeatMessage;
|
||||
import com.njcn.redis.pojo.enums.AppRedisKey;
|
||||
import com.njcn.redis.pojo.enums.RedisKeyEnum;
|
||||
import com.njcn.redis.utils.RedisUtil;
|
||||
import com.njcn.system.api.RocketMqLogFeignClient;
|
||||
import com.njcn.system.pojo.po.RocketmqMsgErrorLog;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
|
||||
import org.apache.rocketmq.spring.core.RocketMQListener;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* 类的介绍: 云前置心跳消息
|
||||
*
|
||||
* @author xuyang
|
||||
* @version 1.0.0
|
||||
* @createTime 2025/9/16
|
||||
*/
|
||||
@Service
|
||||
@RocketMQMessageListener(
|
||||
topic = BusinessTopic.HEART_BEAT_TOPIC,
|
||||
consumerGroup = BusinessTopic.HEART_BEAT_TOPIC,
|
||||
consumeThreadNumber = 10,
|
||||
enableMsgTrace = true
|
||||
)
|
||||
@Slf4j
|
||||
public class CldHeartConsumer extends EnhanceConsumerMessageHandler<CldHeartBeatMessage> implements RocketMQListener<CldHeartBeatMessage> {
|
||||
|
||||
@Resource
|
||||
private RedisUtil redisUtil;
|
||||
@Resource
|
||||
private RocketMqLogFeignClient rocketMqLogFeignClient;
|
||||
|
||||
@Override
|
||||
protected void handleMessage(CldHeartBeatMessage cldHeartBeatMessage) {
|
||||
log.info("分发至云前置心跳数据");
|
||||
String key = RedisKeyEnum.CLD_HEART_BEAT_KEY.getKey().concat(cldHeartBeatMessage.getNodeId() + cldHeartBeatMessage.getProcessNo());
|
||||
redisUtil.saveByKeyWithExpire(key, cldHeartBeatMessage.getNodeId() + cldHeartBeatMessage.getProcessNo(), RedisKeyEnum.CLD_HEART_BEAT_KEY.getTime());
|
||||
}
|
||||
|
||||
|
||||
/***
|
||||
* 通过redis分布式锁判断当前消息所处状态
|
||||
* 1、null 查不到该key的数据,属于第一次消费,放行
|
||||
* 2、fail 上次消息消费时发生异常,放行
|
||||
* 3、being processed 正在处理,打回去
|
||||
* 4、success 最近72小时消费成功,避免重复消费,打回去
|
||||
*/
|
||||
@Override
|
||||
public boolean filter(CldHeartBeatMessage message) {
|
||||
String keyStatus = redisUtil.getStringByKey(AppRedisKey.RMQ_CONSUME_KEY.concat(message.getKey()));
|
||||
if (Objects.isNull(keyStatus) || keyStatus.equalsIgnoreCase(MessageStatus.FAIL)) {
|
||||
redisUtil.saveByKeyWithExpire(AppRedisKey.RMQ_CONSUME_KEY.concat(message.getKey()), MessageStatus.BEING_PROCESSED, 60L);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 消费成功,缓存到redis72小时,避免重复消费
|
||||
*/
|
||||
@Override
|
||||
protected void consumeSuccess(CldHeartBeatMessage message) {
|
||||
redisUtil.saveByKeyWithExpire(AppRedisKey.RMQ_CONSUME_KEY.concat(message.getKey()), MessageStatus.SUCCESS, RedisKeyEnum.ROCKET_MQ_KEY.getTime());
|
||||
}
|
||||
|
||||
/**
|
||||
* 发生异常时,进行错误信息入库保存
|
||||
* 默认没有实现类,子类可以实现该方法,调用feign接口进行入库保存
|
||||
*/
|
||||
@Override
|
||||
protected void saveExceptionMsgLog(CldHeartBeatMessage message, String identity, Exception exception) {
|
||||
redisUtil.saveByKeyWithExpire(AppRedisKey.RMQ_CONSUME_KEY.concat(message.getKey()), MessageStatus.FAIL, RedisKeyEnum.ROCKET_MQ_KEY.getTime());
|
||||
RocketmqMsgErrorLog rocketmqMsgErrorLog = new RocketmqMsgErrorLog();
|
||||
rocketmqMsgErrorLog.setMsgKey(message.getKey());
|
||||
rocketmqMsgErrorLog.setResource(message.getSource());
|
||||
if (identity.equalsIgnoreCase(EnhanceMessageConstant.IDENTITY_SINGLE)) {
|
||||
//数据库字段配置长度200,避免插入失败,大致分析异常原因
|
||||
String exceptionMsg = exception.getMessage();
|
||||
if(exceptionMsg.length() > 200){
|
||||
exceptionMsg = exceptionMsg.substring(0,180);
|
||||
}
|
||||
rocketmqMsgErrorLog.setRecord(exceptionMsg);
|
||||
//如果是当前消息重试的则略过
|
||||
if(!message.getSource().startsWith(EnhanceMessageConstant.RETRY_PREFIX)){
|
||||
//单次消费异常
|
||||
rocketMqLogFeignClient.add(rocketmqMsgErrorLog);
|
||||
}
|
||||
} else {
|
||||
rocketmqMsgErrorLog.setRecord("重试消费" + super.getMaxRetryTimes() + "次,依旧消费失败。");
|
||||
//重试N次后,依然消费异常
|
||||
rocketMqLogFeignClient.add(rocketmqMsgErrorLog);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/***
|
||||
* 处理失败后,是否重试
|
||||
* 一般开启
|
||||
*/
|
||||
@Override
|
||||
protected boolean isRetry() {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/***
|
||||
* 消费失败是否抛出异常,抛出异常后就不再消费了
|
||||
*/
|
||||
@Override
|
||||
protected boolean throwException() {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/***
|
||||
* 调用父类handler处理消息的元信息
|
||||
*/
|
||||
@Override
|
||||
public void onMessage(CldHeartBeatMessage cldHeartBeatMessage) {
|
||||
super.dispatchMessage(cldHeartBeatMessage);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package com.njcn.message.consumer;
|
||||
|
||||
import com.njcn.middle.rocket.constant.EnhanceMessageConstant;
|
||||
import com.njcn.middle.rocket.handler.EnhanceConsumerMessageHandler;
|
||||
import com.njcn.mq.constant.BusinessTopic;
|
||||
import com.njcn.mq.constant.MessageStatus;
|
||||
import com.njcn.mq.message.AppAutoDataMessage;
|
||||
import com.njcn.redis.pojo.enums.AppRedisKey;
|
||||
import com.njcn.redis.pojo.enums.RedisKeyEnum;
|
||||
import com.njcn.redis.utils.RedisUtil;
|
||||
import com.njcn.rt.api.RtFeignClient;
|
||||
import com.njcn.system.api.RocketMqLogFeignClient;
|
||||
import com.njcn.system.pojo.po.RocketmqMsgErrorLog;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
|
||||
import org.apache.rocketmq.spring.core.RocketMQListener;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* 类的介绍:
|
||||
*
|
||||
* @author xuyang
|
||||
* @version 1.0.0
|
||||
* @createTime 2023/8/11 15:32
|
||||
*/
|
||||
@Service
|
||||
@RocketMQMessageListener(
|
||||
topic = BusinessTopic.CLD_HANDLE_REAL_DATA_TOPIC,
|
||||
consumerGroup = BusinessTopic.CLD_HANDLE_REAL_DATA_TOPIC,
|
||||
selectorExpression = BusinessTopic.AppDataTag.RT_TAG,
|
||||
consumeThreadNumber = 10,
|
||||
enableMsgTrace = true
|
||||
)
|
||||
@Slf4j
|
||||
public class RealDataConsumer extends EnhanceConsumerMessageHandler<AppAutoDataMessage> implements RocketMQListener<AppAutoDataMessage> {
|
||||
|
||||
@Resource
|
||||
private RedisUtil redisUtil;
|
||||
@Resource
|
||||
private RocketMqLogFeignClient rocketMqLogFeignClient;
|
||||
@Resource
|
||||
private RtFeignClient rtFeignClient;
|
||||
|
||||
@Override
|
||||
protected void handleMessage(AppAutoDataMessage appAutoDataMessage) {
|
||||
log.info("分发至实时数据");
|
||||
String lineId = appAutoDataMessage.getId() + appAutoDataMessage.getMsg().getClDid();
|
||||
redisUtil.saveByKeyWithExpire("devResponse:" + lineId,200,5L);
|
||||
rtFeignClient.analysis(appAutoDataMessage);
|
||||
}
|
||||
|
||||
|
||||
/***
|
||||
* 通过redis分布式锁判断当前消息所处状态
|
||||
* 1、null 查不到该key的数据,属于第一次消费,放行
|
||||
* 2、fail 上次消息消费时发生异常,放行
|
||||
* 3、being processed 正在处理,打回去
|
||||
* 4、success 最近72小时消费成功,避免重复消费,打回去
|
||||
*/
|
||||
@Override
|
||||
public boolean filter(AppAutoDataMessage message) {
|
||||
String keyStatus = redisUtil.getStringByKey(AppRedisKey.RMQ_CONSUME_KEY.concat(message.getKey()));
|
||||
if (Objects.isNull(keyStatus) || keyStatus.equalsIgnoreCase(MessageStatus.FAIL)) {
|
||||
redisUtil.saveByKeyWithExpire(AppRedisKey.RMQ_CONSUME_KEY.concat(message.getKey()), MessageStatus.BEING_PROCESSED, 60L);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 消费成功,缓存到redis72小时,避免重复消费
|
||||
*/
|
||||
@Override
|
||||
protected void consumeSuccess(AppAutoDataMessage message) {
|
||||
redisUtil.saveByKeyWithExpire(AppRedisKey.RMQ_CONSUME_KEY.concat(message.getKey()), MessageStatus.SUCCESS, RedisKeyEnum.ROCKET_MQ_KEY.getTime());
|
||||
}
|
||||
|
||||
/**
|
||||
* 发生异常时,进行错误信息入库保存
|
||||
* 默认没有实现类,子类可以实现该方法,调用feign接口进行入库保存
|
||||
*/
|
||||
@Override
|
||||
protected void saveExceptionMsgLog(AppAutoDataMessage message, String identity, Exception exception) {
|
||||
redisUtil.saveByKeyWithExpire(AppRedisKey.RMQ_CONSUME_KEY.concat(message.getKey()), MessageStatus.FAIL, RedisKeyEnum.ROCKET_MQ_KEY.getTime());
|
||||
RocketmqMsgErrorLog rocketmqMsgErrorLog = new RocketmqMsgErrorLog();
|
||||
rocketmqMsgErrorLog.setMsgKey(message.getKey());
|
||||
rocketmqMsgErrorLog.setResource(message.getSource());
|
||||
if (identity.equalsIgnoreCase(EnhanceMessageConstant.IDENTITY_SINGLE)) {
|
||||
//数据库字段配置长度200,避免插入失败,大致分析异常原因
|
||||
String exceptionMsg = exception.getMessage();
|
||||
if(exceptionMsg.length() > 200){
|
||||
exceptionMsg = exceptionMsg.substring(0,180);
|
||||
}
|
||||
rocketmqMsgErrorLog.setRecord(exceptionMsg);
|
||||
//如果是当前消息重试的则略过
|
||||
if(!message.getSource().startsWith(EnhanceMessageConstant.RETRY_PREFIX)){
|
||||
//单次消费异常
|
||||
rocketMqLogFeignClient.add(rocketmqMsgErrorLog);
|
||||
}
|
||||
} else {
|
||||
rocketmqMsgErrorLog.setRecord("重试消费" + super.getMaxRetryTimes() + "次,依旧消费失败。");
|
||||
//重试N次后,依然消费异常
|
||||
rocketMqLogFeignClient.add(rocketmqMsgErrorLog);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/***
|
||||
* 处理失败后,是否重试
|
||||
* 一般开启
|
||||
*/
|
||||
@Override
|
||||
protected boolean isRetry() {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/***
|
||||
* 消费失败是否抛出异常,抛出异常后就不再消费了
|
||||
*/
|
||||
@Override
|
||||
protected boolean throwException() {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/***
|
||||
* 调用父类handler处理消息的元信息
|
||||
*/
|
||||
@Override
|
||||
public void onMessage(AppAutoDataMessage appAutoDataMessage) {
|
||||
super.dispatchMessage(appAutoDataMessage);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package com.njcn.message.consumer;
|
||||
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.njcn.csdevice.api.CsTerminalReplyFeignClient;
|
||||
import com.njcn.middle.rocket.constant.EnhanceMessageConstant;
|
||||
import com.njcn.middle.rocket.handler.EnhanceConsumerMessageHandler;
|
||||
import com.njcn.mq.constant.BusinessTopic;
|
||||
import com.njcn.mq.constant.MessageStatus;
|
||||
import com.njcn.mq.message.UpdateLedgerMessage;
|
||||
import com.njcn.redis.pojo.enums.AppRedisKey;
|
||||
import com.njcn.redis.pojo.enums.RedisKeyEnum;
|
||||
import com.njcn.redis.utils.RedisUtil;
|
||||
import com.njcn.system.api.RocketMqLogFeignClient;
|
||||
import com.njcn.system.pojo.po.RocketmqMsgErrorLog;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
|
||||
import org.apache.rocketmq.spring.core.RocketMQListener;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* 类的介绍:接收前置响应台账更新相关信息
|
||||
*
|
||||
* @author xuyang
|
||||
* @version 1.0.0
|
||||
* @createTime 2023/8/11 15:32
|
||||
*/
|
||||
@Service
|
||||
@RocketMQMessageListener(
|
||||
topic = BusinessTopic.REPLY_TOPIC,
|
||||
consumerGroup = BusinessTopic.REPLY_TOPIC,
|
||||
consumeThreadNumber = 10,
|
||||
enableMsgTrace = true
|
||||
)
|
||||
@Slf4j
|
||||
public class UpdateLedgerConsumer extends EnhanceConsumerMessageHandler<UpdateLedgerMessage> implements RocketMQListener<UpdateLedgerMessage> {
|
||||
|
||||
@Resource
|
||||
private RedisUtil redisUtil;
|
||||
@Resource
|
||||
private RocketMqLogFeignClient rocketMqLogFeignClient;
|
||||
@Resource
|
||||
private CsTerminalReplyFeignClient csTerminalReplyFeignClient;
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void handleMessage(UpdateLedgerMessage updateLedgerMessage) {
|
||||
log.info("分发至更新台账响应处理程序");
|
||||
//收到消息修改(cs_terminal_reply)
|
||||
List<UpdateLedgerMessage.HandleData> data = updateLedgerMessage.getData();
|
||||
if (ObjectUtil.isNotEmpty(data)) {
|
||||
data.forEach(item->{
|
||||
if (item.getCode() == 200) {
|
||||
csTerminalReplyFeignClient.updateData(updateLedgerMessage.getGuid(),1,item.getDeviceId());
|
||||
} else {
|
||||
csTerminalReplyFeignClient.updateData(updateLedgerMessage.getGuid(),2,item.getDeviceId());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/***
|
||||
* 通过redis分布式锁判断当前消息所处状态
|
||||
* 1、null 查不到该key的数据,属于第一次消费,放行
|
||||
* 2、fail 上次消息消费时发生异常,放行
|
||||
* 3、being processed 正在处理,打回去
|
||||
* 4、success 最近72小时消费成功,避免重复消费,打回去
|
||||
*/
|
||||
@Override
|
||||
public boolean filter(UpdateLedgerMessage message) {
|
||||
String keyStatus = redisUtil.getStringByKey(AppRedisKey.RMQ_CONSUME_KEY.concat(message.getKey()));
|
||||
if (Objects.isNull(keyStatus) || keyStatus.equalsIgnoreCase(MessageStatus.FAIL)) {
|
||||
redisUtil.saveByKeyWithExpire(AppRedisKey.RMQ_CONSUME_KEY.concat(message.getKey()), MessageStatus.BEING_PROCESSED, 60L);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 消费成功,缓存到redis72小时,避免重复消费
|
||||
*/
|
||||
@Override
|
||||
protected void consumeSuccess(UpdateLedgerMessage message) {
|
||||
redisUtil.saveByKeyWithExpire(AppRedisKey.RMQ_CONSUME_KEY.concat(message.getKey()), MessageStatus.SUCCESS, RedisKeyEnum.ROCKET_MQ_KEY.getTime());
|
||||
}
|
||||
|
||||
/**
|
||||
* 发生异常时,进行错误信息入库保存
|
||||
* 默认没有实现类,子类可以实现该方法,调用feign接口进行入库保存
|
||||
*/
|
||||
@Override
|
||||
protected void saveExceptionMsgLog(UpdateLedgerMessage message, String identity, Exception exception) {
|
||||
redisUtil.saveByKeyWithExpire(AppRedisKey.RMQ_CONSUME_KEY.concat(message.getKey()), MessageStatus.FAIL, RedisKeyEnum.ROCKET_MQ_KEY.getTime());
|
||||
RocketmqMsgErrorLog rocketmqMsgErrorLog = new RocketmqMsgErrorLog();
|
||||
rocketmqMsgErrorLog.setMsgKey(message.getKey());
|
||||
rocketmqMsgErrorLog.setResource(message.getSource());
|
||||
if (identity.equalsIgnoreCase(EnhanceMessageConstant.IDENTITY_SINGLE)) {
|
||||
//数据库字段配置长度200,避免插入失败,大致分析异常原因
|
||||
String exceptionMsg = exception.getMessage();
|
||||
if(exceptionMsg.length() > 200){
|
||||
exceptionMsg = exceptionMsg.substring(0,180);
|
||||
}
|
||||
rocketmqMsgErrorLog.setRecord(exceptionMsg);
|
||||
//如果是当前消息重试的则略过
|
||||
if(!message.getSource().startsWith(EnhanceMessageConstant.RETRY_PREFIX)){
|
||||
//单次消费异常
|
||||
rocketMqLogFeignClient.add(rocketmqMsgErrorLog);
|
||||
}
|
||||
} else {
|
||||
rocketmqMsgErrorLog.setRecord("重试消费" + super.getMaxRetryTimes() + "次,依旧消费失败。");
|
||||
//重试N次后,依然消费异常
|
||||
rocketMqLogFeignClient.add(rocketmqMsgErrorLog);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/***
|
||||
* 处理失败后,是否重试
|
||||
* 一般开启
|
||||
*/
|
||||
@Override
|
||||
protected boolean isRetry() {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/***
|
||||
* 消费失败是否抛出异常,抛出异常后就不再消费了
|
||||
*/
|
||||
@Override
|
||||
protected boolean throwException() {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/***
|
||||
* 调用父类handler处理消息的元信息
|
||||
*/
|
||||
@Override
|
||||
public void onMessage(UpdateLedgerMessage message) {
|
||||
super.dispatchMessage(message);
|
||||
}
|
||||
}
|
||||
49
pom.xml
49
pom.xml
@@ -31,16 +31,47 @@
|
||||
<description>物联网交互模块</description>
|
||||
|
||||
<properties>
|
||||
<!--中间件目标地址-->
|
||||
<middle.server.url>192.168.1.22</middle.server.url>
|
||||
<!--微服务模块发布地址-->
|
||||
<service.server.url>127.0.0.1</service.server.url>
|
||||
<!--docker仓库地址-->
|
||||
<docker.server.url>192.168.1.22</docker.server.url>
|
||||
<!--nacos的ip:port-->
|
||||
|
||||
<!--103本地-->
|
||||
<!-- <middle.server.url>192.168.1.103</middle.server.url>-->
|
||||
<!-- <service.server.url>192.168.1.126</service.server.url>-->
|
||||
<!-- <docker.server.url>192.168.1.103</docker.server.url>-->
|
||||
<!-- <nacos.url>${middle.server.url}:18848</nacos.url>-->
|
||||
<!-- <nacos.namespace>72972c43-3c20-4452-a261-66624e17da97</nacos.namespace>-->
|
||||
|
||||
<!--103线上-->
|
||||
<middle.server.url>192.168.1.103</middle.server.url>
|
||||
<service.server.url>192.168.1.103</service.server.url>
|
||||
<docker.server.url>192.168.1.103</docker.server.url>
|
||||
<nacos.url>${middle.server.url}:18848</nacos.url>
|
||||
<!--服务器发布内容为空-->
|
||||
<nacos.namespace>415a1c87-33aa-47bd-8e25-13cc456c87ed</nacos.namespace>
|
||||
<nacos.namespace></nacos.namespace>
|
||||
|
||||
<!-- <middle.server.url>192.168.1.22</middle.server.url>-->
|
||||
<!-- <service.server.url>192.168.1.126</service.server.url>-->
|
||||
<!-- <docker.server.url>192.168.1.22</docker.server.url>-->
|
||||
<!-- <nacos.url>${middle.server.url}:18848</nacos.url>-->
|
||||
<!-- <nacos.namespace>b0b0dedf-baa9-407f-bef6-988b9e0a640d</nacos.namespace>-->
|
||||
|
||||
<!--浙江现场-->
|
||||
<!-- <middle.server.url>192.168.4.151</middle.server.url>-->
|
||||
<!-- <service.server.url>192.168.4.151</service.server.url>-->
|
||||
<!-- <docker.server.url>192.168.4.151</docker.server.url>-->
|
||||
<!-- <nacos.url>${middle.server.url}:18848</nacos.url>-->
|
||||
<!-- <nacos.namespace></nacos.namespace>-->
|
||||
|
||||
<!--102-->
|
||||
<!-- <middle.server.url>192.168.1.102</middle.server.url>-->
|
||||
<!-- <service.server.url>127.0.0.1</service.server.url>-->
|
||||
<!-- <docker.server.url>192.168.1.102</docker.server.url>-->
|
||||
<!-- <nacos.url>${middle.server.url}:18848</nacos.url>-->
|
||||
<!-- <nacos.namespace>c208a65e-1578-4372-b7c0-97fecd323fe6</nacos.namespace>-->
|
||||
|
||||
<!-- <middle.server.url>192.168.1.27</middle.server.url>-->
|
||||
<!-- <service.server.url>127.0.0.1</service.server.url>-->
|
||||
<!-- <docker.server.url>192.168.1.27</docker.server.url>-->
|
||||
<!-- <nacos.url>${middle.server.url}:18848</nacos.url>-->
|
||||
<!-- <nacos.namespace></nacos.namespace>-->
|
||||
|
||||
<!--sentinel:port-->
|
||||
<sentinel.url>${middle.server.url}:8080</sentinel.url>
|
||||
<!--网关地址,主要用于配置swagger中认证token-->
|
||||
|
||||
Reference in New Issue
Block a user