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();
        }
    }
}
相关推荐
中云DDoS CC防护蔡蔡1 小时前
微信小程序被攻击怎么选择高防产品
服务器·网络安全·微信小程序·小程序·ddos
HPC_fac130520678162 小时前
以科学计算为切入点:剖析英伟达服务器过热难题
服务器·人工智能·深度学习·机器学习·计算机视觉·数据挖掘·gpu算力
yaoxin5211233 小时前
第二十七章 TCP 客户端 服务器通信 - 连接管理
服务器·网络·tcp/ip
Theodore_10224 小时前
4 设计模式原则之接口隔离原则
java·开发语言·设计模式·java-ee·接口隔离原则·javaee
冰帝海岸5 小时前
01-spring security认证笔记
java·笔记·spring
世间万物皆对象5 小时前
Spring Boot核心概念:日志管理
java·spring boot·单元测试
没书读了6 小时前
ssm框架-spring-spring声明式事务
java·数据库·spring
小二·6 小时前
java基础面试题笔记(基础篇)
java·笔记·python
开心工作室_kaic6 小时前
ssm161基于web的资源共享平台的共享与开发+jsp(论文+源码)_kaic
java·开发语言·前端
懒洋洋大魔王6 小时前
RocketMQ的使⽤
java·rocketmq·java-rocketmq