Browse Source

----按照每小时导出统计表,设备在线率和丢包率

main
mengff 11 months ago
parent
commit
1e5db18fbb
  1. 63
      src/main/java/com/example/device/controller/DeviceStatus.java
  2. 20
      src/main/java/com/example/device/entity/Status.java
  3. 44
      src/main/java/com/example/device/service/ExcelExportService.java
  4. 17
      src/main/resources/mapping/StatusMapper.xml

63
src/main/java/com/example/device/controller/DeviceStatus.java

@ -20,6 +20,8 @@ import java.util.stream.Collectors;
import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
@Component @Component
@EnableScheduling @EnableScheduling
@ -34,28 +36,34 @@ public class DeviceStatus {
private ExcelExportService excelExportService; private ExcelExportService excelExportService;
@Scheduled(cron = "0 51 8 * * ?") @Scheduled(cron = "0 20 14 * * ?")
// @Scheduled(cron = "0 0 1,5,7,8,11,14,17,19,21,23") // @Scheduled(cron = "0 0 1,5,7,8,11,14,17,19,21,23")
public void generateDeviceStatus() { public void generateDeviceStatus() {
deviceStatus(); deviceStatus();
} }
public void deviceStatus() { public void deviceStatus() {
Status status = new Status(); Status status = new Status();
List<Device> deviceList = deviceService.SelectList(); List<Device> deviceList = deviceService.SelectList();
for (Device device : deviceList) { for (Device device : deviceList) {
try { try {
InetAddress address = InetAddress.getByName(device.getDeviceIp()); InetAddress address = InetAddress.getByName(device.getDeviceIp());
String lostReat=getPingPacketLossRate(device.getDeviceIp());
boolean reachable = address.isReachable(5000); // Timeout: 5 seconds boolean reachable = address.isReachable(5000); // Timeout: 5 seconds
status.setDeviceNo(device.getDeviceNo()); status.setDeviceNo(device.getDeviceNo());
status.setDeviceName(device.getDeviceName()); status.setDeviceName(device.getDeviceName());
LocalDateTime localDateTime = LocalDateTime.now(); LocalDateTime localDateTime = LocalDateTime.now();
status.setTime(localDateTime); status.setTime(localDateTime);
status.setLostRate(lostReat);
//1-在线 0-离线 //1-在线 0-离线
if (reachable) { if (reachable) {
status.setDeviceStatus(1); status.setDeviceStatus(1);
status.setSuccessRate("100.00%");
} else { } else {
status.setDeviceStatus(0); status.setDeviceStatus(0);
status.setSuccessRate("0.00%");
} }
statusService.Add(status); statusService.Add(status);
} catch (IOException e) { } catch (IOException e) {
@ -66,7 +74,44 @@ public class DeviceStatus {
} }
/** /**
* 计算成功率 * 计算丢包率
*/
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 = 0;
int packetsLost = 0;
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[0].split(" ")[0]);
packetsLost = Integer.parseInt(stats[0].split(" ")[0])-Integer.parseInt(stats[1].split(" ")[0]);
}
}
// Calculate and return the packet loss rate
if (packetsSent > 0) {
return String.format("%.2f%%", (double) packetsLost / packetsSent * 100);
} else {
return "0.00%"; // No packets sent
}
} catch (IOException e) {
e.printStackTrace();
return "-1.00%"; // Error occurred
}
}
/**
* 成功率和丢包率按小时分组
*/ */
public void calculateSuccessRate() { public void calculateSuccessRate() {
@ -79,19 +124,11 @@ public class DeviceStatus {
status.setStartTime(todayStart); status.setStartTime(todayStart);
status.setTime(currentTime); status.setTime(currentTime);
List<Status> listStatus = statusService.list(status); List<Status> listStatus = statusService.list(status);
Map<String, List<Status>> map = listStatus.stream().collect(Collectors.groupingBy(Status::getDeviceName)); Map<Integer, List<Status>> map = listStatus.stream()
for (String name : map.keySet()) { .collect(Collectors.groupingBy(Status -> Status.getTime().getHour()));
// 成功的次数
long successNumber = map.get(name).stream().filter(item -> item.getDeviceStatus() == 1).count();
// 此ip对应的成功率
String successRate = String.format("%.2f%%", (double) successNumber / map.get(name).size() * 100);
ipMap.put(name, successRate);
}
String filePath=CreateNamedExcel(); String filePath=CreateNamedExcel();
excelExportService.exportDataToExcel(ipMap,filePath); excelExportService.exportDataToExcel(map,filePath);
} }
public String CreateNamedExcel() { public String CreateNamedExcel() {
LocalDateTime dateTime = LocalDateTime.now(); LocalDateTime dateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

20
src/main/java/com/example/device/entity/Status.java

@ -87,8 +87,28 @@ public class Status {
private LocalDateTime time; private LocalDateTime time;
public String getSuccessRate() {
return successRate;
}
public void setSuccessRate(String successRate) {
this.successRate = successRate;
}
public String getLostRate() {
return lostRate;
}
public void setLostRate(String lostRate) {
this.lostRate = lostRate;
}
private LocalDateTime startTime; private LocalDateTime startTime;
private String deviceIp; private String deviceIp;
private String successRate;
private String lostRate;
} }

44
src/main/java/com/example/device/service/ExcelExportService.java

@ -1,4 +1,5 @@
package com.example.device.service; package com.example.device.service;
import com.example.device.entity.Status;
import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -8,36 +9,53 @@ import java.io.IOException;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit; import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map; import java.util.Map;
@Service @Service
public class ExcelExportService { public class ExcelExportService {
public void exportDataToExcel(Map<String, String> ipMap, String filePath) { public void exportDataToExcel(Map<Integer, List<Status>> ipMap, String filePath) {
Workbook workbook = new XSSFWorkbook(); Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("设备故障率"); for (Map.Entry<Integer, List<Status>> entry : ipMap.entrySet()) {
Sheet sheet = workbook.createSheet(entry.getKey()+"小时设备故障率");
LocalDateTime dateTime = LocalDateTime.now(); LocalDateTime dateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = dateTime.format(formatter); String formattedDateTime = dateTime.format(formatter);
int rowNum = 0; int rowNum = 0;
for (String name : ipMap.keySet()) { Row row = sheet.createRow(rowNum);
Row row = sheet.createRow(rowNum++); row.createCell(0).setCellValue("设备名称");
row.createCell(0).setCellValue(name); row.createCell(1).setCellValue("设备IP");
row.createCell(1).setCellValue(ipMap.get(name)); row.createCell(2).setCellValue("在线率");
row.createCell(2).setCellValue(formattedDateTime); row.createCell(3).setCellValue("丢包率");
CellStyle style = workbook.createCellStyle(); CellStyle style = workbook.createCellStyle();
// 应用样式到单元格 // 应用样式到单元格
row.getCell(0).setCellStyle(style); row.getCell(0).setCellStyle(style);
row.getCell(1).setCellStyle(style); row.getCell(1).setCellStyle(style);
row.getCell(2).setCellStyle(style); row.getCell(2).setCellStyle(style);
row.getCell(3).setCellStyle(style);
rowNum = 1;
List<Status> groupItems = entry.getValue();
for (Status ignored : groupItems) {
row= sheet.createRow(rowNum++);
row.createCell(0).setCellValue(ignored.getDeviceName());
row.createCell(1).setCellValue(ignored.getDeviceIp());
row.createCell(2).setCellValue(ignored.getSuccessRate());
row.createCell(3).setCellValue(ignored.getLostRate());
// 应用样式到单元格
row.getCell(0).setCellStyle(style);
row.getCell(1).setCellStyle(style);
row.getCell(2).setCellStyle(style);
row.getCell(3).setCellStyle(style);
}
} }
try (FileOutputStream outputStream = new FileOutputStream(filePath)) { try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
workbook.write(outputStream); workbook.write(outputStream);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
System.out.println("excel写入成功!!!!!!");
} }
} }

17
src/main/resources/mapping/StatusMapper.xml

@ -8,6 +8,8 @@
<result column="device_name" jdbcType="VARCHAR" property="deviceName"/> <result column="device_name" jdbcType="VARCHAR" property="deviceName"/>
<result column="device_status" jdbcType="INTEGER" property="deviceStatus"/> <result column="device_status" jdbcType="INTEGER" property="deviceStatus"/>
<result column="device_ip" jdbcType="VARCHAR" property="deviceIp"/> <result column="device_ip" jdbcType="VARCHAR" property="deviceIp"/>
<result column="success_rate" jdbcType="VARCHAR" property="successRate"/>
<result column="lost_rate" jdbcType="VARCHAR" property="lostRate"/>
</resultMap> </resultMap>
@ -27,6 +29,13 @@
<if test="status.time != null"> <if test="status.time != null">
time, time,
</if> </if>
<if test="status.successRate != null">
success_rate,
</if>
<if test="status.lostRate != null">
lost_rate,
</if>
</trim> </trim>
<trim prefix="VALUES (" suffix=")" suffixOverrides=","> <trim prefix="VALUES (" suffix=")" suffixOverrides=",">
<if test="status.deviceNo != null"> <if test="status.deviceNo != null">
@ -41,6 +50,12 @@
<if test="status.time != null"> <if test="status.time != null">
#{status.time,jdbcType=DATE}, #{status.time,jdbcType=DATE},
</if> </if>
<if test="status.successRate != null">
#{status.successRate,jdbcType=VARCHAR},
</if>
<if test="status.lostRate != null">
#{status.lostRate,jdbcType=VARCHAR},
</if>
</trim> </trim>
</insert> </insert>
@ -49,7 +64,7 @@
</sql> </sql>
<select id="listStatus" parameterType="com.example.device.entity.Status" resultMap="BaseResultMap"> <select id="listStatus" parameterType="com.example.device.entity.Status" resultMap="BaseResultMap">
select s.id, s.device_no, s.device_name, s.device_status, s.time, d.device_ip select s.id, s.device_no, s.device_name, s.device_status, s.time, d.device_ip,s.success_rate,s.lost_rate
from status s from status s
LEFT JOIN device d on s.device_no = d.device_no LEFT JOIN device d on s.device_no = d.device_no
<where> <where>

Loading…
Cancel
Save