济菏高速数据中心代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

201 lines
8.5 KiB

package com.zc.business.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.util.StringUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.zc.business.domain.DcDevice;
import com.zc.business.domain.Status;
import com.zc.business.enums.UniversalEnum;
import com.zc.business.service.IDcDeviceService;
import com.zc.business.service.impl.ExcelExportService;
import com.zc.business.service.impl.StatusService;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.*;
import java.util.stream.Collectors;
@Component
@EnableScheduling
public class DeviceStatus {
//@Autowired
//private IDcDeviceService deviceService;
//
//@Autowired
//private StatusService statusService;
//
//@Autowired
//private ExcelExportService excelExportService;
//每天凌晨0点到晚上23点整点测试设备状态
// @Scheduled(cron = "0 0 0-23 * * ?")
// @Scheduled(cron = "0 0 1,5,7,8,11,14,17,19,21,23")
public void deviceStatus() {
IDcDeviceService deviceService = SpringUtils.getBean(IDcDeviceService.class);
StatusService statusService = SpringUtils.getBean(StatusService.class);
ExecutorService executor = Executors.newFixedThreadPool(UniversalEnum.ONE_HUNDRED.getNumber());
LambdaQueryWrapper<DcDevice> lambdaQueryWrapper = new LambdaQueryWrapper<>();
List<DcDevice> deviceList = deviceService.list(lambdaQueryWrapper);
List<Future<Void>> futures = new ArrayList<>();
for (DcDevice device : deviceList) {
Callable<Void> task = () -> {
if (Objects.equals(device.getDeviceType(), UniversalEnum.EIGHT.getValue()) || Objects.equals(device.getDeviceType(), UniversalEnum.FIFTEEN.getValue())) {
AjaxResult deviceByIotDeviceId = deviceService.getDeviceByIotDeviceId(device.getIotDeviceId());
String deviceState = ((JSONObject) JSON.toJSON(deviceByIotDeviceId.get("data"))).getString("deviceState");
if (Objects.equals(deviceState, UniversalEnum.ON_LINE.getValue())) {
extracted(statusService, device, true, UniversalEnum.ZERO_PERCENT.getValue());
} else {
extracted(statusService, device, false, UniversalEnum.ONE_HUNDRED_PERCENT.getValue());
}
} else {
if (StringUtil.isNotEmpty(device.getDeviceIp())) {
InetAddress address = InetAddress.getByName(device.getDeviceIp());
boolean reachable = address.isReachable(UniversalEnum.FIVE_THOUSAND.getNumber()); // Timeout: 5 seconds
extracted(statusService, device, reachable, getPingPacketLossRate(device.getDeviceIp()));
} else {
extracted(statusService, device, false, UniversalEnum.ONE_HUNDRED_PERCENT.getValue());
}
}
return null;
};
futures.add(executor.submit(task));
}
for (Future<Void> future : futures) {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
executor.shutdown();
}
private void extracted(StatusService statusService, DcDevice device, boolean reachable, String packetLossRate) {
Status status = new Status();
status.setDeviceNo(device.getStakeMark());
status.setDeviceName(device.getDeviceName());
status.setDeviceIp(device.getDeviceIp());
status.setDeviceId(device.getId());
LocalDateTime localDateTime = LocalDateTime.now();
status.setTime(localDateTime);
status.setLostRate(packetLossRate);
if (reachable) {
status.setDeviceStatus(UniversalEnum.ONE.getValue());
status.setSuccessRate(UniversalEnum.ONE_HUNDRED_PERCENT.getValue());
} else {
status.setDeviceStatus(UniversalEnum.ZERO.getValue());
status.setSuccessRate(UniversalEnum.ZERO_PERCENT.getValue());
}
statusService.Add(status);
}
/**
* 计算丢包率
*/
public String getPingPacketLossRate(String ipAddress) {
try {
// Execute the ping command
Process process = Runtime.getRuntime().exec("ping -c 4 " + ipAddress); // Sending 4 ICMP Echo Request packets
// Read the output of the command
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
int packetsSent = UniversalEnum.ZERO.getNumber();
int packetsLost = UniversalEnum.ZERO.getNumber();
while ((line = reader.readLine()) != null) {
// Check for lines containing packet loss information
if (line.contains("packets transmitted")) {
// Extract the number of packets sent and lost
String[] stats = line.split(", ");
packetsSent = Integer.parseInt(stats[UniversalEnum.ZERO.getNumber()].split(UniversalEnum.BLANK_SPACE.getValue())[UniversalEnum.ZERO.getNumber()]);
packetsLost = Integer.parseInt(stats[UniversalEnum.ZERO.getNumber()].split(UniversalEnum.BLANK_SPACE.getValue())[UniversalEnum.ZERO.getNumber()]) - Integer.parseInt(stats[UniversalEnum.ONE.getNumber()].split(UniversalEnum.BLANK_SPACE.getValue())[UniversalEnum.ZERO.getNumber()]);
}
}
// Calculate and return the packet loss rate
if (packetsSent > UniversalEnum.ZERO.getNumber()) {
return String.format("%.2f%%", (double) packetsLost / packetsSent * UniversalEnum.ONE_HUNDRED.getNumber());
} else {
return UniversalEnum.ZERO_PERCENT.getValue(); // No packets sent
}
} catch (IOException e) {
e.printStackTrace();
return UniversalEnum.MINUS_ONE_PERCENT.getValue(); // Error occurred
}
}
/**
* 成功率和丢包率按小时分组
* 每天17点 23点 30分导出excel表
*/
// @Scheduled(cron = "0 30 17,23 * * ?")
public void calculateSuccessRate() {
StatusService statusService = SpringUtils.getBean(StatusService.class);
ExcelExportService excelExportService = SpringUtils.getBean(ExcelExportService.class);
LocalDateTime todayStart = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS);
LocalDateTime currentTime = LocalDateTime.now();
Status status = new Status();
status.setStartTime(todayStart);
status.setTime(currentTime);
List<Status> listStatus = statusService.list(status);
//根据时间分组
Map<Integer, List<Status>> map = listStatus.stream()
.collect(Collectors.groupingBy(Status -> Status.getTime().getHour()));
//根据类型分组
Map<String, List<Status>> maps = listStatus.stream().filter(iteam -> iteam.getType() != null).collect(Collectors.groupingBy(Status::getType));
String filePath = CreateNamedExcel();
excelExportService.exportDataToExcel(map, maps, filePath);
}
public String CreateNamedExcel() {
LocalDateTime dateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(UniversalEnum.TIME_FORMAT_ALL.getValue());
String formattedDateTime = dateTime.format(formatter);
//修改成服务器地址
String filePath = "/home/excel/" + formattedDateTime + "--deviceStatus.xlsx";
try (Workbook workbook = new XSSFWorkbook()) {
FileOutputStream fileOut = new FileOutputStream(filePath);
workbook.write(fileOut);
System.out.println("Empty named Excel created successfully.");
} catch (IOException e) {
e.printStackTrace();
}
return filePath;
}
}