以下是使用Java OSHI库获取当前服务器的CPU和内存、硬盘占用情况的示例代码:

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.OperatingSystem;

public class ServerMonitor {

    public static void main(String[] args) {
        SystemInfo systemInfo = new SystemInfo();

        // 获取CPU信息
        CentralProcessor processor = systemInfo.getHardware().getProcessor();
        System.out.println("CPU使用率: " + processor.getSystemCpuLoad() * 100 + "%");

        // 获取内存信息
        GlobalMemory memory = systemInfo.getHardware().getMemory();
        long totalMemory = memory.getTotal();
        long availableMemory = memory.getAvailable();
        long usedMemory = totalMemory - availableMemory;
        System.out.println("总内存: " + formatSize(totalMemory));
        System.out.println("已用内存: " + formatSize(usedMemory));
        System.out.println("可用内存: " + formatSize(availableMemory));

        // 获取硬盘信息
        OperatingSystem os = systemInfo.getOperatingSystem();
        FileSystem fileSystem = os.getFileSystem();
        OSFileStore[] fileStores = fileSystem.getFileStores();
        for (OSFileStore fs : fileStores) {
            long totalSpace = fs.getTotalSpace();
            long usableSpace = fs.getUsableSpace();
            long usedSpace = totalSpace - usableSpace;
            System.out.println("磁盘" + fs.getName() + "总空间: " + formatSize(totalSpace));
            System.out.println("磁盘" + fs.getName() + "已用空间: " + formatSize(usedSpace));
            System.out.println("磁盘" + fs.getName() + "可用空间: " + formatSize(usableSpace));
        }
    }

    private static String formatSize(long size) {
        if (size < 1024) {
            return size + "B";
        } else if (size < 1024 * 1024) {
            return String.format("%.2fKB", size / 1024.0);
        } else if (size < 1024 * 1024 * 1024) {
            return String.format("%.2fMB", size / (1024.0 * 1024));
        } else {
            return String.format("%.2fGB", size / (1024.0 * 1024 * 1024));
        }
    }

}

在上面的示例代码中,我们先创建了一个SystemInfo对象,然后通过它获取了CPU、内存和硬盘的信息。其中,CentralProcessorGlobalMemory分别表示CPU和内存信息,FileSystemOSFileStore分别表示文件系统和磁盘信息。我们可以通过这些对象提供的方法获取相关的指标数据,例如CPU使用率、内存总量、可用内存、已用内存、磁盘总空间、可用空间、已用空间等。最后,我们通过formatSize()方法将数据格式化为易读的形式,方便查看

java oshi获取当前服务器的CPU和内存硬盘占用情况

原文地址: http://www.cveoy.top/t/topic/htJS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录