Java获取服务器CPU、内存、磁盘信息

在Java中监控服务器的CPU、内存和磁盘等信息

文章目录

    • [使用 Java Management API](#使用 Java Management API)
    • 使用第三方库OSHI
    • [使用 JMX(Java Management Extensions)](#使用 JMX(Java Management Extensions))
    • 使用命令行工具ProcessBuilder或Runtime.exec()
      • [1. 监控CPU使用情况](#1. 监控CPU使用情况)
      • [2. 监控内存使用情况](#2. 监控内存使用情况)
      • [3. 监控磁盘使用情况](#3. 监控磁盘使用情况)
      • [4. 组合监控](#4. 组合监控)

使用 Java Management API

通过Java自带的ManagementFactory和MXBean接口获取系统级别信息,如CPU负载和内存使用情况。

示例代码:

import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.MemoryMXBean;

public class SystemMonitor {
    public static void main(String[] args) {
        OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
        MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();

        System.out.println("CPU负载: " + osBean.getSystemLoadAverage());
        System.out.println("堆内存使用: " + memoryBean.getHeapMemoryUsage().getUsed() + " bytes");
    }
}

使用第三方库OSHI

OSHI:一个强大的Java库,用于获取操作系统和硬件信息,支持CPU、内存、磁盘等监控。示例代码:

import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.software.os.OperatingSystem;

public class SystemMonitor {
    public static void main(String[] args) {
        SystemInfo systemInfo = new SystemInfo();
        CentralProcessor processor = systemInfo.getHardware().getProcessor();
        OperatingSystem os = systemInfo.getOperatingSystem();

        System.out.println("CPU负载: " + processor.getSystemCpuLoadBetweenTicks() * 100 + "%");
        System.out.println("总内存: " + systemInfo.getHardware().getMemory().getTotal() + " bytes");
    }
}

import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import oshi.software.os.NetworkIF;
import oshi.software.os.OperatingSystem;
import oshi.software.os.OperatingSystemVersion;

public class SystemMetrics {

    public static void main(String[] args) {
        SystemInfo systemInfo = new SystemInfo();
        CentralProcessor processor = systemInfo.getHardware().getProcessor();
        GlobalMemory memory = systemInfo.getHardware().getMemory();
        OperatingSystem os = systemInfo.getOperatingSystem();
        FileSystem fileSystem = os.getFileSystem();
        NetworkIF[] networkIFs = os.getNetworkIFs();

        // CPU 使用率
        double cpuLoad = processor.getSystemCpuLoad() * 100;
        System.out.println("CPU Load: " + cpuLoad + "%");

        // 内存使用情况
        long totalMemory = memory.getTotal();
        long usedMemory = totalMemory - memory.getAvailable();
        System.out.println("Used Memory: " + (usedMemory / (1024 * 1024)) + " MB");
        System.out.println("Total Memory: " + (totalMemory / (1024 * 1024)) + " MB");

        // 磁盘使用情况
        for (OSFileStore fileStore : fileSystem.getFileStores()) {
            System.out.println("Disk: " + fileStore.getMount() +
                    ", Total: " + (fileStore.getTotalSpace() / (1024 * 1024)) + " MB" +
                    ", Usable: " + (fileStore.getUsableSpace() / (1024 * 1024)) + " MB" +
                    ", Used: " + ((fileStore.getTotalSpace() - fileStore.getUsableSpace()) / (1024 * 1024)) + " MB");
        }

        // 网络带宽使用情况
        for (NetworkIF net : networkIFs) {
            long[] prevIO = net.getBytesRecv();
            long[] currIO = net.getBytesSent();
            System.out.println("Network Interface: " + net.getName());
            System.out.println("Received: " + (prevIO[0] / 1024) + " KB, Sent: " + (currIO[0] / 1024) + " KB");
        }
    }
}

使用 JMX(Java Management Extensions)

可以通过JMX监控Java应用的性能指标,并可以监控JVM自身的内存和线程使用情况。

使用命令行工具ProcessBuilder或Runtime.exec()

可以通过执行系统命令(如top, df, free等)获取系统信息,使用ProcessBuilder来运行命令并获取输出。

示例代码:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class CommandLineMonitor {
    public static void main(String[] args) {
        try {
            Process process = new ProcessBuilder("sh", "-c", "top -bn1 | grep 'Cpu'").start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

来执行系统命令并获取输出

在Java中使用命令行工具监控服务器的CPU、内存和磁盘使用情况,可以通过ProcessBuilder或Runtime.exec()来执行系统命令并获取输出。以下是实现的示例代码:

1. 监控CPU使用情况

可以使用top或mpstat命令来获取CPU使用情况。以下示例使用top命令:

i

mport java.io.BufferedReader;
import java.io.InputStreamReader;

public class CpuMonitor {
    public static void main(String[] args) {
        try {
            ProcessBuilder processBuilder = new ProcessBuilder("sh", "-c", "top -bn1 | grep 'Cpu'");
            Process process = processBuilder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("CPU使用情况: " + line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2. 监控内存使用情况

可以使用free命令获取内存使用情况:

public class MemoryMonitor {
    public static void main(String[] args) {
        try {
            ProcessBuilder processBuilder = new ProcessBuilder("sh", "-c", "free -h");
            Process process = processBuilder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("内存使用情况: " + line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3. 监控磁盘使用情况

可以使用df命令来获取磁盘使用情况:

public class DiskMonitor {
    public static void main(String[] args) {
        try {
            ProcessBuilder processBuilder = new ProcessBuilder("sh", "-c", "df -h");
            Process process = processBuilder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("磁盘使用情况: " + line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

4. 组合监控

可以将这些功能组合到一个程序中,以便在定时任务中执行:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class SystemMonitor {
    public static void main(String[] args) {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        
        scheduler.scheduleAtFixedRate(() -> {
            monitorCpu();
            monitorMemory();
            monitorDisk();
        }, 0, 10, TimeUnit.SECONDS);
    }

    private static void monitorCpu() {
        executeCommand("top -bn1 | grep 'Cpu'");
    }

    private static void monitorMemory() {
        executeCommand("free -h");
    }

    private static void monitorDisk() {
        executeCommand("df -h");
    }

    private static void executeCommand(String command) {
        try {
            ProcessBuilder processBuilder = new ProcessBuilder("sh", "-c", command);
            Process process = processBuilder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
相关推荐
风吹落叶花飘荡2 分钟前
从零开始的 vue项目部署到服务器详细步骤(vue项目build打包+nginx部署+配置ssl证书)
服务器·vue.js·nginx
很楠不爱4 分钟前
Qt——信号和槽
服务器·数据库·qt
BLOB_1010015 分钟前
【折腾一上午】Java POI 导出 Excel 自适应列宽行高
java·excel
神技圈子8 分钟前
【linux经典工具】作为一个合格的开发人员怎能不会tmux
linux·运维·服务器
布值倒区什么name16 分钟前
日常记录,使用springboot,vue2,easyexcel使实现字段的匹配导入
java·spring boot·后端
single59419 分钟前
【综合算法学习】(第十篇)
java·数据结构·c++·vscode·学习·算法·leetcode
Bold!20 分钟前
最新ubuntu22.04 下列软件包有未满足的依赖关系 解决方案
linux·运维·服务器
wclass-zhengge21 分钟前
SpringBoot篇(自动装配原理)
java·spring boot·后端
哎呦没29 分钟前
中小企业设备管理效率提升:Spring Boot系统设计
java·spring boot·后端
ZWZhangYu32 分钟前
【MyBatis源码】SqlSource对象创建流程
java·tomcat·mybatis