From ce20d61a59885f97caee4e262d03c423745585d6 Mon Sep 17 00:00:00 2001 From: gaoguangchao <443960933@qq.com> Date: Tue, 16 Jul 2024 18:11:12 +0800 Subject: [PATCH] =?UTF-8?q?=E8=AE=BE=E5=A4=87=E5=9C=A8=E7=BA=BF=E7=9B=91?= =?UTF-8?q?=E6=B5=8B=E6=96=B0=E5=A2=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../business/constant/RedisKeyConstants.java | 4 + .../com/zc/business/domain/OnlineLog.java | 236 ++++++++++++ .../com/zc/business/domain/OnlineSum.java | 182 +++++++++ .../zc/business/mapper/OnlineLogMapper.java | 9 + .../business/service/IOnlineLogService.java | 12 + .../service/impl/OnlineLogServiceImpl.java | 19 + .../zc/business/task/DeviceOnlineTask.java | 352 ++++++++++++++++++ .../mapper/business/OnlineLogMapper.xml | 38 ++ 8 files changed, 852 insertions(+) create mode 100644 zc-business/src/main/java/com/zc/business/domain/OnlineLog.java create mode 100644 zc-business/src/main/java/com/zc/business/domain/OnlineSum.java create mode 100644 zc-business/src/main/java/com/zc/business/mapper/OnlineLogMapper.java create mode 100644 zc-business/src/main/java/com/zc/business/service/IOnlineLogService.java create mode 100644 zc-business/src/main/java/com/zc/business/service/impl/OnlineLogServiceImpl.java create mode 100644 zc-business/src/main/java/com/zc/business/task/DeviceOnlineTask.java create mode 100644 zc-business/src/main/resources/mapper/business/OnlineLogMapper.xml diff --git a/zc-business/src/main/java/com/zc/business/constant/RedisKeyConstants.java b/zc-business/src/main/java/com/zc/business/constant/RedisKeyConstants.java index cd29ee5e..71ea7e2a 100644 --- a/zc-business/src/main/java/com/zc/business/constant/RedisKeyConstants.java +++ b/zc-business/src/main/java/com/zc/business/constant/RedisKeyConstants.java @@ -49,4 +49,8 @@ public class RedisKeyConstants * 交通流 */ public static final String TRAFFIC_FLOW = "trafficFlow"; + /* + * 设备在线监测 + * */ + public static final String DEVICE_ONLINE = "deviceOnline"; } diff --git a/zc-business/src/main/java/com/zc/business/domain/OnlineLog.java b/zc-business/src/main/java/com/zc/business/domain/OnlineLog.java new file mode 100644 index 00000000..a94b0dd4 --- /dev/null +++ b/zc-business/src/main/java/com/zc/business/domain/OnlineLog.java @@ -0,0 +1,236 @@ +package com.zc.business.domain; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.utils.DateUtils; +import com.zc.business.enums.UniversalEnum; +import org.springframework.format.annotation.DateTimeFormat; + +import java.io.Serializable; +import java.time.LocalDateTime; +import java.util.Arrays; +import java.util.Date; + +public class OnlineLog implements Serializable { + private static final long serialVersionUID = 1L; + private long id; + private Long deviceId; + private String deviceIp; + private String deviceName; + private String stakeMark; + private String deviceStatus; + private String networkQuality;//网络质量 + private int sendCount;//发送数 + private int receiveCount;//返回数 + private int lossCount;//丢包数 + private String lossRate;//丢包率 + private double rttAvg;//平均往返时延 + @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private LocalDateTime monitorTime; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public Long getDeviceId() { + return deviceId; + } + + public void setDeviceId(Long deviceId) { + this.deviceId = deviceId; + } + + public String getDeviceIp() { + return deviceIp; + } + + public void setDeviceIp(String deviceIp) { + this.deviceIp = deviceIp; + } + + public String getDeviceName() { + return deviceName; + } + + public void setDeviceName(String deviceName) { + this.deviceName = deviceName; + } + + public String getStakeMark() { + return stakeMark; + } + + public void setStakeMark(String stakeMark) { + this.stakeMark = stakeMark; + } + + public String getDeviceStatus() { + return deviceStatus; + } + + public void setDeviceStatus(String deviceStatus) { + this.deviceStatus = deviceStatus; + } + + public String getNetworkQuality() { + return networkQuality; + } + + public void setNetworkQuality(String networkQuality) { + this.networkQuality = networkQuality; + } + + public int getSendCount() { + return sendCount; + } + + public void setSendCount(int sendCount) { + this.sendCount = sendCount; + } + + public int getReceiveCount() { + return receiveCount; + } + + public void setReceiveCount(int receiveCount) { + this.receiveCount = receiveCount; + } + + public int getLossCount() { + return lossCount; + } + + public void setLossCount(int lossCount) { + this.lossCount = lossCount; + } + + public String getLossRate() { + return lossRate; + } + + public void setLossRate(String lossRate) { + this.lossRate = lossRate; + } + + public double getRttAvg() { + return rttAvg; + } + + public void setRttAvg(double rttAvg) { + this.rttAvg = rttAvg; + } + + public LocalDateTime getMonitorTime() { + return monitorTime; + } + + public void setMonitorTime(LocalDateTime monitorTime) { + this.monitorTime = monitorTime; + } + + @Override + public String toString() { + return "OnlineLog{" + + "id=" + id + + ", deviceId=" + deviceId + + ", deviceIp='" + deviceIp + '\'' + + ", deviceName='" + deviceName + '\'' + + ", stakeMark='" + stakeMark + '\'' + + ", deviceStatus='" + deviceStatus + '\'' + + ", networkQuality='" + networkQuality + '\'' + + ", sendCount=" + sendCount + + ", receiveCount=" + receiveCount + + ", lossCount=" + lossCount + + ", lossRate='" + lossRate + '\'' + + ", rttAvg=" + rttAvg + + ", monitorTime=" + monitorTime + + '}'; + } + + public static class LogBuilder{ + OnlineLog onlineLog = new OnlineLog(); + public LogBuilder setDeviceStatus(String deviceStatus) { + onlineLog.setDeviceStatus(deviceStatus); + return this; + } + public LogBuilder setSendCount(int sendCount) { + onlineLog.setSendCount(sendCount); + return this; + } + public LogBuilder setReceiveCount(int receiveCount) { + onlineLog.setReceiveCount(receiveCount); + return this; + } + public LogBuilder setRttAvg(double rttAvg) { + onlineLog.setRttAvg(rttAvg); + return this; + } + public OnlineLog build(DcDevice device) { + onlineLog.setDeviceId(device.getId()); + onlineLog.setDeviceIp(device.getDeviceIp()); + onlineLog.setDeviceName(device.getDeviceName()); + onlineLog.setStakeMark(device.getStakeMark()); + String lossRate = String.format("%.2f%%", (double) onlineLog.getLossCount() / onlineLog.getSendCount() * 100); + onlineLog.setLossRate(lossRate); + double rttAvg = onlineLog.getRttAvg(); + if(rttAvg > 0 && rttAvg <= 30){ + onlineLog.setNetworkQuality(NetworkQuality.GOOD.getValue()); + }else if(rttAvg >30 && rttAvg <= 100){ + onlineLog.setNetworkQuality(NetworkQuality.NORMAL.getValue()); + }else { + onlineLog.setNetworkQuality(NetworkQuality.BAD.getValue()); + } + onlineLog.setLossCount(onlineLog.getSendCount() - onlineLog.getReceiveCount()); + onlineLog.setMonitorTime(LocalDateTime.now()); + return onlineLog; + } + public OnlineLog buildBad(DcDevice device){ + onlineLog.setDeviceId(device.getId()); + onlineLog.setDeviceIp(device.getDeviceIp()); + onlineLog.setDeviceName(device.getDeviceName()); + onlineLog.setStakeMark(device.getStakeMark()); + onlineLog.setNetworkQuality(NetworkQuality.BAD.getValue()); + onlineLog.setMonitorTime(LocalDateTime.now()); + onlineLog.setSendCount(4); + onlineLog.setReceiveCount(0); + onlineLog.setLossCount(4); + onlineLog.setLossRate("100.00%"); + onlineLog.setRttAvg(0); + onlineLog.setDeviceStatus(UniversalEnum.ZERO.getValue()); + return onlineLog; + } + public OnlineLog buildGood(DcDevice device){ + onlineLog.setDeviceId(device.getId()); + onlineLog.setDeviceIp(device.getDeviceIp()); + onlineLog.setDeviceName(device.getDeviceName()); + onlineLog.setStakeMark(device.getStakeMark()); + onlineLog.setNetworkQuality(NetworkQuality.GOOD.getValue()); + onlineLog.setMonitorTime(LocalDateTime.now()); + onlineLog.setSendCount(4); + onlineLog.setReceiveCount(4); + onlineLog.setLossCount(0); + onlineLog.setLossRate("0.00%"); + onlineLog.setRttAvg(30); + onlineLog.setDeviceStatus(UniversalEnum.ONE.getValue()); + return onlineLog; + } + } + enum NetworkQuality{ + GOOD("优"), + NORMAL("良"), + BAD("差"); + private final String value; + String getValue() { + return value; + } + NetworkQuality(String value) { + this.value = value; + } + } + +} diff --git a/zc-business/src/main/java/com/zc/business/domain/OnlineSum.java b/zc-business/src/main/java/com/zc/business/domain/OnlineSum.java new file mode 100644 index 00000000..93a030d1 --- /dev/null +++ b/zc-business/src/main/java/com/zc/business/domain/OnlineSum.java @@ -0,0 +1,182 @@ +package com.zc.business.domain; + +import com.fasterxml.jackson.annotation.JsonFormat; +import org.springframework.format.annotation.DateTimeFormat; + +import java.util.Date; + +public class OnlineSum implements java.io.Serializable { + private static final long serialVersionUID = 1L; + private long id; + private long deviceId; + private String deviceName; + private String deviceIp; + private String stakeMark; + private String deviceStatus; + private int sendCount;//发送数 + private int receiveCount;//返回数 + private int lossCount;//丢包数 + private String lossRate;//丢包率 + private double rttAvg;//平均往返时延 + private String networkQuality;//网络质量 + @DateTimeFormat(pattern = "yyyy-MM-dd") + @JsonFormat(pattern = "yyyy-MM-dd") + private Date statisticalDate;//统计日期 + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public Long getDeviceId() { + return deviceId; + } + + public void setDeviceId(Long deviceId) { + this.deviceId = deviceId; + } + + public String getDeviceName() { + return deviceName; + } + + public void setDeviceName(String deviceName) { + this.deviceName = deviceName; + } + + public String getDeviceIp() { + return deviceIp; + } + + public void setDeviceIp(String deviceIp) { + this.deviceIp = deviceIp; + } + + public String getStakeMark() { + return stakeMark; + } + + public void setStakeMark(String stakeMark) { + this.stakeMark = stakeMark; + } + + public String getDeviceStatus() { + return deviceStatus; + } + + public void setDeviceStatus(String deviceStatus) { + this.deviceStatus = deviceStatus; + } + + public int getSendCount() { + return sendCount; + } + + public void setSendCount(int sendCount) { + this.sendCount = sendCount; + } + + public int getReceiveCount() { + return receiveCount; + } + + public void setReceiveCount(int receiveCount) { + this.receiveCount = receiveCount; + } + + public int getLossCount() { + return lossCount; + } + + public void setLossCount(int lossCount) { + this.lossCount = lossCount; + } + + public String getLossRate() { + return lossRate; + } + + public void setLossRate(String lossRate) { + this.lossRate = lossRate; + } + + public double getRttAvg() { + return rttAvg; + } + + public void setRttAvg(double rttAvg) { + this.rttAvg = rttAvg; + } + + public String getNetworkQuality() { + return networkQuality; + } + + public void setNetworkQuality(String networkQuality) { + this.networkQuality = networkQuality; + } + + public Date getStatisticalDate() { + return statisticalDate; + } + + public void setStatisticalDate(Date statisticalDate) { + this.statisticalDate = statisticalDate; + } + + @Override + public String toString() { + return "OnlineSum{" + + "id=" + id + + ", deviceId='" + deviceId + '\'' + + ", deviceName='" + deviceName + '\'' + + ", deviceIp='" + deviceIp + '\'' + + ", stakeMark='" + stakeMark + '\'' + + ", deviceStatus='" + deviceStatus + '\'' + + ", sendCount=" + sendCount + + ", receiveCount=" + receiveCount + + ", lossCount=" + lossCount + + ", lossRate='" + lossRate + '\'' + + ", rttAvg=" + rttAvg + + ", networkQuality='" + networkQuality + '\'' + + ", statisticalDate=" + statisticalDate + + '}'; + } + + public OnlineSum copyFromLog(OnlineLog onlineLog) { + this.deviceId = onlineLog.getDeviceId(); + this.deviceName = onlineLog.getDeviceName(); + this.deviceIp = onlineLog.getDeviceIp(); + this.stakeMark = onlineLog.getStakeMark(); + this.deviceStatus = onlineLog.getDeviceStatus(); + this.sendCount = onlineLog.getSendCount(); + this.receiveCount = onlineLog.getReceiveCount(); + this.lossCount = onlineLog.getLossCount(); + this.lossRate = onlineLog.getLossRate(); + this.rttAvg = onlineLog.getRttAvg(); + this.networkQuality = onlineLog.getNetworkQuality(); + this.statisticalDate = new Date(); + return this; + } + + public OnlineSum incrementSummary(OnlineLog onlineLog) { + double rtt = this.rttAvg*this.sendCount+onlineLog.getRttAvg()*onlineLog.getSendCount(); + this.deviceStatus = onlineLog.getDeviceStatus(); + this.sendCount += onlineLog.getSendCount(); + this.receiveCount += onlineLog.getReceiveCount(); + this.lossCount += onlineLog.getLossCount(); + this.lossRate = String.format("%.2f%%", (this.sendCount==0?0:(double)this.lossCount/this.sendCount)*100); + this.rttAvg = this.sendCount==0?0:rtt/this.sendCount; + if(this.rttAvg > 0 && this.rttAvg <= 30){ + this.networkQuality = OnlineLog.NetworkQuality.GOOD.getValue(); + }else if(this.rttAvg >30 && this.rttAvg <= 100){ + this.networkQuality = OnlineLog.NetworkQuality.NORMAL.getValue(); + }else { + this.networkQuality = OnlineLog.NetworkQuality.BAD.getValue(); + } + return this; + } +} diff --git a/zc-business/src/main/java/com/zc/business/mapper/OnlineLogMapper.java b/zc-business/src/main/java/com/zc/business/mapper/OnlineLogMapper.java new file mode 100644 index 00000000..ada5bc3a --- /dev/null +++ b/zc-business/src/main/java/com/zc/business/mapper/OnlineLogMapper.java @@ -0,0 +1,9 @@ +package com.zc.business.mapper; + +import com.zc.business.domain.OnlineLog; + +import java.util.List; + +public interface OnlineLogMapper { + int addBatch(List onlineLogs); +} diff --git a/zc-business/src/main/java/com/zc/business/service/IOnlineLogService.java b/zc-business/src/main/java/com/zc/business/service/IOnlineLogService.java new file mode 100644 index 00000000..b40e6ff7 --- /dev/null +++ b/zc-business/src/main/java/com/zc/business/service/IOnlineLogService.java @@ -0,0 +1,12 @@ +package com.zc.business.service; + +import com.zc.business.domain.OnlineLog; + +import java.util.List; + +/** + * 设备在线日志 + */ +public interface IOnlineLogService { + int addBatch(List list); +} diff --git a/zc-business/src/main/java/com/zc/business/service/impl/OnlineLogServiceImpl.java b/zc-business/src/main/java/com/zc/business/service/impl/OnlineLogServiceImpl.java new file mode 100644 index 00000000..4ec7ac6d --- /dev/null +++ b/zc-business/src/main/java/com/zc/business/service/impl/OnlineLogServiceImpl.java @@ -0,0 +1,19 @@ +package com.zc.business.service.impl; + +import com.zc.business.domain.OnlineLog; +import com.zc.business.mapper.OnlineLogMapper; +import com.zc.business.service.IOnlineLogService; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.List; +@Service +public class OnlineLogServiceImpl implements IOnlineLogService { + @Resource + private OnlineLogMapper onlineLogMapper; + + @Override + public int addBatch(List list) { + return onlineLogMapper.addBatch(list); + } +} diff --git a/zc-business/src/main/java/com/zc/business/task/DeviceOnlineTask.java b/zc-business/src/main/java/com/zc/business/task/DeviceOnlineTask.java new file mode 100644 index 00000000..f8b35257 --- /dev/null +++ b/zc-business/src/main/java/com/zc/business/task/DeviceOnlineTask.java @@ -0,0 +1,352 @@ +package com.zc.business.task; + +import com.alibaba.excel.util.DateUtils; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.core.redis.RedisCache; +import com.ruoyi.common.utils.spring.SpringUtils; +import com.zc.business.constant.RedisKeyConstants; +import com.zc.business.domain.DcDevice; +import com.zc.business.domain.OnlineLog; +import com.zc.business.domain.OnlineSum; +import com.zc.business.enums.UniversalEnum; +import com.zc.business.service.IDcDeviceService; +import com.zc.business.service.IOnlineLogService; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.InetAddress; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.temporal.ChronoUnit; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import org.slf4j.Logger; +import org.springframework.util.ObjectUtils; + +import javax.tools.JavaFileManager; +import javax.xml.stream.Location; + +/** + * 设备在线率检测 + */ +@Component("DeviceOnline") +public class DeviceOnlineTask { + Logger logger = LoggerFactory.getLogger(DeviceOnlineTask.class); + IDcDeviceService dcDeviceService = SpringUtils.getBean(IDcDeviceService.class); + IOnlineLogService onlineLogService = SpringUtils.getBean(IOnlineLogService.class); + RedisCache redisCache = SpringUtils.getBean(RedisCache.class); + ExecutorService executorService; + final static int BATCH_SIZE = 100; + /** + * 设备在线率检测一小时执行一次 + */ + public void deviceOnlineTask() { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + List deviceList = dcDeviceService.list(lambdaQueryWrapper); + Map onlineLogMap = new ConcurrentHashMap<>(); + executorService = Executors.newFixedThreadPool(UniversalEnum.ONE_HUNDRED.getNumber()); + for (DcDevice device : deviceList) { + executorService.submit(()->{ + try { + String ipAddress = device.getDeviceIp(); + OnlineLog onlineLog; + if(ipAddress == null || ipAddress.isEmpty()){ + //IP为空,查询物联状态 + onlineLog = getIotDeviceStatus(device); + }else { + if(isReachable(ipAddress)){ + onlineLog = sendPingPacket(device); + }else { + onlineLog = new OnlineLog.LogBuilder().buildBad(device); + } + } + if(onlineLog != null){ + onlineLogMap.put(device.getId(), onlineLog); + } + } catch (Exception e) { + e.printStackTrace(); + logger.error("Error pinging device {},message {}", device.getDeviceIp(), e.getMessage()); + } + }); + } + shutdown(); + //批量处理数据 + addBatch(new ArrayList<>(onlineLogMap.values())); + } + + /** + * 是否可达 + * @param ipAddress IP地址 + * @return @see boolean + */ + private boolean isReachable(String ipAddress) { + try { + InetAddress address = InetAddress.getByName(ipAddress); + return address.isReachable(UniversalEnum.FIVE_THOUSAND.getNumber()); + } catch (IOException e) { + e.printStackTrace(); + return false; + } + } + + /** + * 发送ping包(通用) + * @param device ip地址 + * @return @see OnlineLog + */ + private OnlineLog sendPingPacket(DcDevice device){ + switch (SystemType.checkSystem()){ + case LINUX_SYSTEM: + return sendPingPacketOfLinux(device); + case WIN_SYSTEM: + return sendPingPacketOfWindows(device); + case AIX_SYSTEM: + case UNIX_SYSTEM: + throw new UnsupportedOperationException("不支持的系统类型"); + default: + throw new IllegalStateException("未知的系统类型,无法执行命令"); + } + } + + /** + * 发送ping包(linux) + * @param device ip地址 + * @return @see OnlineLog + */ + public OnlineLog sendPingPacketOfLinux(DcDevice device) { + OnlineLog.LogBuilder logBuilder = new OnlineLog.LogBuilder(); + try { + // Execute the ping command + Process process = Runtime.getRuntime().exec(PingCommand.LINUX_PING.getValue() + device.getDeviceIp()); // Sending 4 ICMP Echo Request packets + // Read the output of the command + BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); + int transmitted = 0; + int received = 0; + double rttAvg = 0.0; + String line; + while ((line = reader.readLine()) != null) { + if (line.contains("packets transmitted")) { + String[] stats = line.split(", "); + transmitted = Integer.parseInt(stats[0].split(" ")[0]); + received = Integer.parseInt(stats[1].split(" ")[0]); + } + if(line.contains("rtt")){ + String[] stats = line.split(" "); + rttAvg = Double.parseDouble(stats[3].split("/")[1]); + } + } + return logBuilder.setDeviceStatus(UniversalEnum.ONE.getValue()) + .setSendCount(transmitted) + .setReceiveCount(received) + .setRttAvg(rttAvg) + .build(device); + } catch (IOException e) { + e.printStackTrace(); + return logBuilder.buildBad(device); + } + } + + public OnlineLog sendPingPacketOfWindows(DcDevice device) { + OnlineLog.LogBuilder logBuilder = new OnlineLog.LogBuilder(); + ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "ping", "-n", "4", device.getDeviceIp()); + try { + // 启动进程 + Process process = processBuilder.start(); + // 读取命令的标准输出 + BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(),"GBK")); + int transmitted = 0; + int received = 0; + double rttAvg = 0.0; + String line; + while ((line = reader.readLine()) != null) { + if (line.contains("已发送")) { + String[] stats = line.split(","); + transmitted = Integer.parseInt(stats[0].split("= ")[1]); + received = Integer.parseInt(stats[1].split("= ")[1]); + } + if(line.contains("平均")){ + String[] stats = line.split(","); + rttAvg = Double.parseDouble(stats[2].split("= ")[1].substring(0, stats[2].split("= ")[1].length()-2)); + } + } + // 等待进程结束 + process.waitFor(); + return logBuilder.setDeviceStatus(UniversalEnum.ONE.getValue()) + .setSendCount(transmitted) + .setReceiveCount(received) + .setRttAvg(rttAvg) + .build(device); + } catch (IOException | InterruptedException e) { + e.printStackTrace(); + return logBuilder.buildBad(device); + } + } + + /** + * 关闭线程池 + */ + public void shutdown() { + executorService.shutdown(); // 发起关闭请求,不再接受新任务,但会等待已提交的任务完成 + try { + // 等待所有任务完成,或者等待直到超时 + if (!executorService.awaitTermination(55, TimeUnit.MINUTES)) { + // 超时后尝试停止所有正在执行的任务 + executorService.shutdownNow(); // 这不会等待正在执行的任务完成 + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); // 重新设置中断状态 + executorService.shutdownNow(); // 尝试停止所有任务 + } + } + + /** + * 批量处理数据 + * @param onlineLogs 待处理数据 + */ + private void addBatch(List onlineLogs) { + for (int i = 0; i < onlineLogs.size(); i += BATCH_SIZE) { + int endIndex = Math.min(i + BATCH_SIZE, onlineLogs.size()); + List subList = onlineLogs.subList(i, endIndex); + int rows = onlineLogService.addBatch(subList); + if(rows >0) { + for (OnlineLog onlineLog : subList) { + incrementSummary(onlineLog); + } + } + } + } + /** + * 增量汇总,当天数据增量汇总到Redis + */ + private void incrementSummary(OnlineLog onlineLog) { + // 获取当天日期 + String date = DateUtils.format(new Date(), "yyyy-MM-dd"); + if(ObjectUtils.isEmpty(onlineLog) || ObjectUtils.isEmpty(onlineLog.getDeviceId())){ + System.out.println("数据为空"); + } + long deviceId = onlineLog.getDeviceId(); + OnlineSum onlineSum = redisCache.getCacheMapValue(RedisKeyConstants.DEVICE_ONLINE , date+":"+deviceId); + if (ObjectUtils.isEmpty(onlineSum)){ + onlineSum = new OnlineSum().copyFromLog(onlineLog); + redisCache.setCacheMapValue(RedisKeyConstants.DEVICE_ONLINE, date+onlineLog.getDeviceId(), onlineSum); + Long ttl = redisCache.getExpire(RedisKeyConstants.DEVICE_ONLINE); + if(ttl == -1) redisCache.expire(RedisKeyConstants.DEVICE_ONLINE,getTimeout()); + }else { + //增量计算 + onlineSum.incrementSummary(onlineLog); + redisCache.setCacheMapValue(RedisKeyConstants.DEVICE_ONLINE, date+onlineLog.getDeviceId(), onlineSum); + } + } + + /** + * 获取设备在线状态 + * @param device 设备信息 + * @return @see PingResult + */ + private OnlineLog getIotDeviceStatus(DcDevice device){ + OnlineLog.LogBuilder logBuilder = new OnlineLog.LogBuilder(); + try { + AjaxResult deviceByIotDeviceId = dcDeviceService.getDeviceByIotDeviceId(device.getIotDeviceId()); + if (Objects.equals(String.valueOf(deviceByIotDeviceId.get("code")), UniversalEnum.TWO_HUNDRED.getValue())){ + String deviceState = ((JSONObject) JSON.toJSON(deviceByIotDeviceId.get("data"))).getString("deviceState"); + if (!ObjectUtils.isEmpty(deviceState) && Objects.equals(deviceState, UniversalEnum.ON_LINE.getValue())) { + return logBuilder.buildGood(device); + } + } + return logBuilder.buildBad(device); + } catch (Exception e) { + e.printStackTrace(); + return logBuilder.buildBad(device); + } + } + + private long getTimeout(){ + // 获取当前时间 + ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault()); + // 获取今天午夜的时间(即今天的00:00:00) + ZonedDateTime midnight = now.truncatedTo(ChronoUnit.DAYS); + // 计算两个时间点之间的秒数差 + long secondsToday = ChronoUnit.SECONDS.between(midnight, now); + // 一天的秒数 + long secondsInDay = ChronoUnit.SECONDS.between(midnight, midnight.plusDays(1)); + // 当天剩余的秒数 + return secondsInDay - secondsToday; + } + enum SystemType { + WIN_SYSTEM("win"), + LINUX_SYSTEM("linux"), + AIX_SYSTEM("aix"), + UNIX_SYSTEM("unix"), + UNKNOWN_SYSTEM("unknown"); + String value; + String getValue() { + return value; + } + SystemType(String value) { + this.value = value; + } + static SystemType checkSystem(){ + String osName = System.getProperty("os.name").toLowerCase(); + if (osName.contains(SystemType.WIN_SYSTEM.getValue())) { + return SystemType.WIN_SYSTEM; + } else if (osName.contains(SystemType.LINUX_SYSTEM.getValue())) { + return SystemType.LINUX_SYSTEM; + } else if (osName.contains(SystemType.AIX_SYSTEM.getValue())) { + return SystemType.AIX_SYSTEM; + } else if (osName.contains(SystemType.UNIX_SYSTEM.getValue())) { + return SystemType.UNIX_SYSTEM; + } + return SystemType.UNKNOWN_SYSTEM; + } + } + enum PingCommand{ + LINUX_PING("ping -c 4 "), + WINDOWS_PING("ping "); + private final String value; + + String getValue() { + return value; + } + PingCommand(String value) { + this.value = value; + } + } + + public static void main(String[] args) { + // 假设你要ping的主机地址 + String host = "10.0.111.11"; + + // 构建ping命令,注意:Windows和Unix/Linux的ping命令略有不同 + // Windows: ping -n 4 www.google.com + // Unix/Linux: ping -c 4 www.google.com + ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "ping", "-n", "4", host); + + try { + // 启动进程 + Process process = processBuilder.start(); + + // 读取命令的标准输出 + BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(),"GBK")); + String line; + while ((line = reader.readLine()) != null) { + System.out.println(line); + } + + // 等待进程结束 + int exitCode = process.waitFor(); + System.out.println("\nExited with error code : " + exitCode); + + } catch (IOException | InterruptedException e) { + e.printStackTrace(); + } + } +} diff --git a/zc-business/src/main/resources/mapper/business/OnlineLogMapper.xml b/zc-business/src/main/resources/mapper/business/OnlineLogMapper.xml new file mode 100644 index 00000000..de914f3d --- /dev/null +++ b/zc-business/src/main/resources/mapper/business/OnlineLogMapper.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + insert into dc_online_log + ( + device_id,device_name,device_ip,stake_mark,device_status,send_count, + receive_count,loss_count,loss_rate,network_quality,rtt_avg,monitor_time + ) + values + + ( + #{item.deviceId}, + #{item.deviceName}, + #{item.deviceIp}, + #{item.stakeMark}, + #{item.deviceStatus}, + #{item.sendCount}, + #{item.receiveCount}, + #{item.lossCount}, + #{item.lossRate}, + #{item.networkQuality}, + #{item.rttAvg}, + #{item.monitorTime} + ) + + + +