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();
        }
    }
}
相关推荐
xlsw_1 小时前
java全栈day20--Web后端实战(Mybatis基础2)
java·开发语言·mybatis
神仙别闹2 小时前
基于java的改良版超级玛丽小游戏
java
远游客07132 小时前
centos stream 8下载安装遇到的坑
linux·服务器·centos
黄油饼卷咖喱鸡就味增汤拌孜然羊肉炒饭2 小时前
SpringBoot如何实现缓存预热?
java·spring boot·spring·缓存·程序员
暮湫2 小时前
泛型(2)
java
超爱吃士力架2 小时前
邀请逻辑
java·linux·后端
南宫生3 小时前
力扣-图论-17【算法学习day.67】
java·学习·算法·leetcode·图论
转码的小石3 小时前
12/21java基础
java
李小白663 小时前
Spring MVC(上)
java·spring·mvc
GoodStudyAndDayDayUp3 小时前
IDEA能够从mapper跳转到xml的插件
xml·java·intellij-idea