本文目录导读:

我来为您提供一个完整的Java系统监控实现案例,包含CPU、内存、磁盘和网络监控。
系统监控核心类
SystemMonitor.java
package com.monitor;
import com.sun.management.OperatingSystemMXBean;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
/**
* 系统监控器 - 负责采集系统各项指标
*/
public class SystemMonitor {
private OperatingSystemMXBean osBean;
private long lastCpuTime;
private long lastProcessCpuTime;
public SystemMonitor() {
osBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
initCpuTime();
}
private void initCpuTime() {
lastCpuTime = osBean.getCpuTime();
lastProcessCpuTime = osBean.getProcessCpuTime();
}
/**
* 获取CPU使用率(百分比)
*/
public double getCpuUsage() {
try {
Thread.sleep(500); // 采样间隔
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
long cpuTime = osBean.getCpuTime();
long processCpuTime = osBean.getProcessCpuTime();
double cpuUsage = (double)(processCpuTime - lastProcessCpuTime) * 100.0 /
(cpuTime - lastCpuTime);
lastCpuTime = cpuTime;
lastProcessCpuTime = processCpuTime;
return Math.round(cpuUsage * 100.0) / 100.0;
}
/**
* 获取物理内存信息
*/
public MemoryInfo getMemoryInfo() {
MemoryInfo info = new MemoryInfo();
info.setTotalMemory(osBean.getTotalPhysicalMemorySize());
info.setFreeMemory(osBean.getFreePhysicalMemorySize());
info.setUsedMemory(info.getTotalMemory() - info.getFreeMemory());
info.setUsedPercent((info.getUsedMemory() * 100.0) / info.getTotalMemory());
return info;
}
/**
* 获取JVM内存信息
*/
public JvmMemoryInfo getJvmMemoryInfo() {
Runtime runtime = Runtime.getRuntime();
JvmMemoryInfo info = new JvmMemoryInfo();
info.setMaxMemory(runtime.maxMemory());
info.setTotalMemory(runtime.totalMemory());
info.setFreeMemory(runtime.freeMemory());
info.setUsedMemory(info.getTotalMemory() - info.getFreeMemory());
return info;
}
/**
* 获取系统信息
*/
public SystemInfo getSystemInfo() throws Exception {
SystemInfo info = new SystemInfo();
info.setOsName(osBean.getName());
info.setOsVersion(osBean.getVersion());
info.setArch(osBean.getArch());
info.setCpuCores(osBean.getAvailableProcessors());
info.setJvmVersion(System.getProperty("java.version"));
info.setJavaHome(System.getProperty("java.home"));
InetAddress localHost = InetAddress.getLocalHost();
info.setHostName(localHost.getHostName());
info.setHostAddress(localHost.getHostAddress());
return info;
}
/**
* 获取磁盘使用情况
*/
public List<DiskInfo> getDiskInfo() {
List<DiskInfo> disks = new ArrayList<>();
File[] roots = File.listRoots();
for (File root : roots) {
if (root.canRead()) {
DiskInfo disk = new DiskInfo();
disk.setPath(root.getPath());
disk.setTotalSpace(root.getTotalSpace());
disk.setFreeSpace(root.getFreeSpace());
disk.setUsableSpace(root.getUsableSpace());
disk.setUsedSpace(root.getTotalSpace() - root.getFreeSpace());
disk.setUsedPercent((disk.getUsedSpace() * 100.0) / disk.getTotalSpace());
disks.add(disk);
}
}
return disks;
}
/**
* 获取网络信息
*/
public List<NetworkInfo> getNetworkInfo() throws SocketException {
List<NetworkInfo> networks = new ArrayList<>();
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface = interfaces.nextElement();
if (networkInterface.isUp() && !networkInterface.isLoopback()) {
NetworkInfo info = new NetworkInfo();
info.setName(networkInterface.getName());
info.setDisplayName(networkInterface.getDisplayName());
byte[] mac = networkInterface.getHardwareAddress();
if (mac != null) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i],
(i < mac.length - 1) ? "-" : ""));
}
info.setMacAddress(sb.toString());
}
Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
if (addr.isSiteLocalAddress()) {
info.setIpAddress(addr.getHostAddress());
break;
}
}
info.setSpeed(networkInterface.getSpeed());
networks.add(info);
}
}
return networks;
}
/**
* 获取进程列表
*/
public List<ProcessInfo> getProcessList() {
List<ProcessInfo> processes = new ArrayList<>();
try {
// 这里可以扩展为通过系统命令获取进程信息
// 示例使用ProcessBuilder
ProcessBuilder pb = new ProcessBuilder("ps", "-e");
Process process = pb.start();
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
boolean first = true;
while ((line = reader.readLine()) != null) {
if (first) {
first = false;
continue;
}
String[] parts = line.trim().split("\\s+");
if (parts.length >= 4) {
ProcessInfo info = new ProcessInfo();
info.setPid(parts[0]);
info.setUser(parts[1]);
info.setCpu(parts[2] + "%");
info.setMemory(parts[3] + "%");
processes.add(info);
}
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return processes;
}
}
数据模型类
package com.monitor;
import lombok.Data;
import java.io.Serializable;
@Data
public class MemoryInfo implements Serializable {
private long totalMemory; // 物理内存总量
private long freeMemory; // 物理内存空闲
private long usedMemory; // 物理内存已用
private double usedPercent; // 使用百分比
}
@Data
public class JvmMemoryInfo implements Serializable {
private long maxMemory; // 最大内存
private long totalMemory; // JVM内存总量
private long usedMemory; // JVM已用内存
private long freeMemory; // JVM空闲内存
}
@Data
public class SystemInfo implements Serializable {
private String osName; // 操作系统名称
private String osVersion; // 操作系统版本
private String arch; // 系统架构
private int cpuCores; // CPU核心数
private String jvmVersion; // JVM版本
private String javaHome; // Java安装路径
private String hostName; // 主机名
private String hostAddress; // 主机IP
}
@Data
public class DiskInfo implements Serializable {
private String path; // 磁盘路径
private long totalSpace; // 磁盘总空间
private long freeSpace; // 磁盘可用空间
private long usableSpace; // 磁盘剩余可用空间
private long usedSpace; // 磁盘已用空间
private double usedPercent; // 使用百分比
}
@Data
public class NetworkInfo implements Serializable {
private String name; // 网络接口名称
private String displayName; // 显示名称
private String macAddress; // MAC地址
private String ipAddress; // IP地址
private long speed; // 速率
}
@Data
public class ProcessInfo implements Serializable {
private String pid; // 进程ID
private String user; // 用户
private String cpu; // CPU使用率
private String memory; // 内存使用率
}
Web接口实现
MonitorController.java
package com.monitor.controller;
import com.monitor.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import java.net.SocketException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/monitor")
public class MonitorController {
@Autowired
private SystemMonitor systemMonitor;
@GetMapping("/overview")
public Map<String, Object> getOverview() {
Map<String, Object> result = new HashMap<>();
try {
// CPU使用率
double cpuUsage = systemMonitor.getCpuUsage();
result.put("cpuUsage", cpuUsage);
// 内存信息
MemoryInfo memoryInfo = systemMonitor.getMemoryInfo();
result.put("memory", memoryInfo);
// JVM内存信息
JvmMemoryInfo jvmMemoryInfo = systemMonitor.getJvmMemoryInfo();
result.put("jvmMemory", jvmMemoryInfo);
// 系统信息
SystemInfo systemInfo = systemMonitor.getSystemInfo();
result.put("system", systemInfo);
// 磁盘信息
List<DiskInfo> diskInfo = systemMonitor.getDiskInfo();
result.put("disks", diskInfo);
// 网络信息
List<NetworkInfo> networkInfo = systemMonitor.getNetworkInfo();
result.put("networks", networkInfo);
result.put("success", true);
} catch (Exception e) {
result.put("success", false);
result.put("error", e.getMessage());
}
return result;
}
@GetMapping("/cpu")
public double getCpuUsage() {
return systemMonitor.getCpuUsage();
}
@GetMapping("/memory")
public Map<String, Object> getMemory() {
Map<String, Object> result = new HashMap<>();
result.put("physical", systemMonitor.getMemoryInfo());
result.put("jvm", systemMonitor.getJvmMemoryInfo());
return result;
}
@GetMapping("/disks")
public List<DiskInfo> getDisks() {
return systemMonitor.getDiskInfo();
}
@GetMapping("/networks")
public List<NetworkInfo> getNetworks() throws SocketException {
return systemMonitor.getNetworkInfo();
}
@GetMapping("/processes")
public List<ProcessInfo> getProcesses() {
return systemMonitor.getProcessList();
}
@GetMapping("/system")
public SystemInfo getSystem() throws Exception {
return systemMonitor.getSystemInfo();
}
}
图形界面监控(JavaFX)
MonitorGUI.java
package com.monitor.ui;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.util.Duration;
import javafx.scene.chart.*;
/**
* 系统监控图形界面(JavaFX实现)
*/
public class MonitorGUI extends Application {
private SystemMonitor monitor = new SystemMonitor();
private Label cpuLabel, memoryLabel, diskLabel;
private ProgressBar cpuBar, memoryBar, diskBar;
private LineChart<String, Number> cpuChart;
private XYChart.Series<String, Number> cpuSeries;
private int timeCounter = 0;
@Override
public void start(Stage stage) {
stage.setTitle("系统监控器");
// 创建主布局
BorderPane root = new BorderPane();
root.setPadding(new Insets(10));
// 顶部标题栏
Label titleLabel = new Label("系统资源监控");
titleLabel.setStyle("-fx-font-size: 20px; -fx-font-weight: bold;");
root.setTop(titleLabel);
// 中部图表区域
VBox centerBox = new VBox(10);
centerBox.getChildren().addAll(createServerInfoPanel(), createChartPanel());
root.setCenter(centerBox);
// 底部实时信息
root.setBottom(createStatusBar());
// 启动实时更新
startMonitoring();
Scene scene = new Scene(root, 800, 600);
stage.setScene(scene);
stage.show();
}
private GridPane createServerInfoPanel() {
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(10));
// CPU
grid.add(new Label("CPU使用率:"), 0, 0);
cpuBar = new ProgressBar();
cpuBar.setPrefWidth(200);
grid.add(cpuBar, 1, 0);
cpuLabel = new Label("0%");
grid.add(cpuLabel, 2, 0);
// 内存
grid.add(new Label("内存使用率:"), 0, 1);
memoryBar = new ProgressBar();
memoryBar.setPrefWidth(200);
grid.add(memoryBar, 1, 1);
memoryLabel = new Label("0%");
grid.add(memoryLabel, 2, 1);
// 磁盘
grid.add(new Label("磁盘使用率:"), 0, 2);
diskBar = new ProgressBar();
diskBar.setPrefWidth(200);
grid.add(diskBar, 1, 2);
diskLabel = new Label("0%");
grid.add(diskLabel, 2, 2);
return grid;
}
private VBox createChartPanel() {
// 创建CPU使用率折线图
CategoryAxis xAxis = new CategoryAxis();
NumberAxis yAxis = new NumberAxis(0, 100, 10);
cpuChart = new LineChart<>(xAxis, yAxis);
cpuChart.setTitle("CPU使用率曲线");
cpuChart.setPrefHeight(300);
cpuSeries = new XYChart.Series<>();
cpuSeries.setName("CPU使用率");
cpuChart.getData().add(cpuSeries);
VBox chartBox = new VBox(10);
chartBox.setPadding(new Insets(10));
chartBox.getChildren().add(cpuChart);
return chartBox;
}
private HBox createStatusBar() {
HBox statusBar = new HBox(10);
statusBar.setPadding(new Insets(10));
statusBar.setStyle("-fx-background-color: #f0f0f0;");
Label statusLabel = new Label("系统状态:");
Label statusValue = new Label("运行中");
statusValue.setStyle("-fx-text-fill: green;");
statusBar.getChildren().addAll(statusLabel, statusValue);
return statusBar;
}
private void startMonitoring() {
Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(2), event -> {
updateMonitoringData();
}));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
}
private void updateMonitoringData() {
// 更新CPU信息
double cpuUsage = monitor.getCpuUsage();
cpuBar.setProgress(cpuUsage / 100.0);
cpuLabel.setText(String.format("%.2f%%", cpuUsage));
// 更新图表
timeCounter++;
cpuSeries.getData().add(new XYChart.Data<>(
String.valueOf(timeCounter), cpuUsage));
// 保留最近30个数据点
if (cpuSeries.getData().size() > 30) {
cpuSeries.getData().remove(0);
}
// 更新内存信息
MemoryInfo memoryInfo = monitor.getMemoryInfo();
double memoryUsage = memoryInfo.getUsedPercent();
memoryBar.setProgress(memoryUsage / 100.0);
memoryLabel.setText(String.format("%.2f%%", memoryUsage));
// 更新磁盘信息
List<DiskInfo> disks = monitor.getDiskInfo();
if (!disks.isEmpty()) {
double totalSpace = 0;
double usedSpace = 0;
for (DiskInfo disk : disks) {
totalSpace += disk.getTotalSpace();
usedSpace += disk.getUsedSpace();
}
double diskUsage = (usedSpace / totalSpace) * 100;
diskBar.setProgress(diskUsage / 100.0);
diskLabel.setText(String.format("%.2f%%", diskUsage));
}
}
public static void main(String[] args) {
launch(args);
}
}
项目配置文件
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>system-monitor</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.7.0</version>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>
<!-- JavaFX (用于GUI监控) -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>11.0.2</version>
</dependency>
<!-- JSON处理 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.3</version>
</dependency>
<!-- 测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.7.0</version>
</plugin>
</plugins>
</build>
</project>
使用示例
简单测试类
package com.monitor;
public class MonitorTest {
public static void main(String[] args) {
SystemMonitor monitor = new SystemMonitor();
try {
// 获取系统信息
SystemInfo systemInfo = monitor.getSystemInfo();
System.out.println("操作系统: " + systemInfo.getOsName() + " " +
systemInfo.getOsVersion());
System.out.println("CPU核心数: " + systemInfo.getCpuCores());
System.out.println("主机名: " + systemInfo.getHostName());
// 获取CPU使用率
double cpuUsage = monitor.getCpuUsage();
System.out.println("CPU使用率: " + cpuUsage + "%");
// 获取内存信息
MemoryInfo memoryInfo = monitor.getMemoryInfo();
System.out.println("物理内存: " +
formatSize(memoryInfo.getTotalMemory()));
System.out.println("已用内存: " +
formatSize(memoryInfo.getUsedMemory()));
System.out.println("内存使用率: " +
String.format("%.2f%%", memoryInfo.getUsedPercent()));
// 获取磁盘信息
List<DiskInfo> disks = monitor.getDiskInfo();
for (DiskInfo disk : disks) {
System.out.println("磁盘 " + disk.getPath() + ": " +
formatSize(disk.getUsedSpace()) + " / " +
formatSize(disk.getTotalSpace()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String formatSize(long size) {
if (size >= 1024 * 1024 * 1024) {
return String.format("%.2f GB", size / (1024.0 * 1024 * 1024));
} else if (size >= 1024 * 1024) {
return String.format("%.2f MB", size / (1024.0 * 1024));
} else if (size >= 1024) {
return String.format("%.2f KB", size / 1024.0);
} else {
return size + " B";
}
}
}
这个完整的系统监控案例包含了:
- 核心监控功能:CPU、内存、磁盘、网络、进程监控
- Web接口:RESTful API提供监控数据
- 图形界面:JavaFX实现的实时监控面板
- 扩展性:可以根据需要添加邮件告警、日志记录等功能
使用时只需运行主类或通过Web接口获取监控数据即可。