Java 獲取系統各項引數

HuDu發表於2021-02-04

介紹

OSHI是Java的免費的基於JNA的(本機)作業系統和硬體資訊庫。它不需要安裝任何其他本機庫,並且旨在提供一種跨平臺的實現來檢索系統資訊,例如OS版本,程式,記憶體和CPU使用率,磁碟和分割槽,裝置,感測器等。

oshi支援的功能

  • 計算機系統和韌體,底板
  • 作業系統和版本/內部版本
  • 物理(核心)和邏輯(超執行緒)CPU
  • 系統和每個處理器的負載百分比和滴答計數器
  • CPU正常執行時間,程式和執行緒
  • 程式正常執行時間,CPU,記憶體使用率
  • 已使用/可用的物理和虛擬記憶體
  • 掛載的檔案系統(型別,可用空間和總空間)
  • 磁碟驅動器(型號,序列號,大小)和分割槽
  • 網路介面(IP,頻寬輸入/輸出)
  • 電池狀態(電量百分比,剩餘時間)
  • 連線的顯示器(帶有EDID資訊)
  • USB裝置
  • 感測器(溫度,風扇速度,電壓)

API

Java 獲取系統各項引數

Java 獲取系統各項引數

Java 獲取系統各項引數

Java 獲取系統各項引數

Java 獲取系統各項引數

Java 獲取系統各項引數

Java 獲取系統各項引數

Java 獲取系統各項引數

Java 獲取系統各項引數

具體實現

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 獲取系統資訊 -->
<dependency>
    <groupId>com.github.oshi</groupId>
    <artifactId>oshi-core</artifactId>
    <version>5.3.6</version>
</dependency>
<!--常用工具類 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
</dependency>
<!-- 阿里JSON解析器 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.47</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

工具類

public class SystemInfoUtils {
    private static final int OSHI_WAIT_SECOND = 1000;
    private static SystemInfo systemInfo = new SystemInfo();
    private static HardwareAbstractionLayer hardware = systemInfo.getHardware();
    private static OperatingSystem operatingSystem = systemInfo.getOperatingSystem();

    public static JSONObject getCpuInfo() {
        JSONObject cpuInfo = new JSONObject();
        CentralProcessor processor = hardware.getProcessor();
        // CPU資訊
        long[] prevTicks = processor.getSystemCpuLoadTicks();
        Util.sleep(OSHI_WAIT_SECOND);
        long[] ticks = processor.getSystemCpuLoadTicks();
        long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[CentralProcessor.TickType.NICE.getIndex()];
        long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()] - prevTicks[CentralProcessor.TickType.IRQ.getIndex()];
        long softirq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()] - prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()];
        long steal = ticks[CentralProcessor.TickType.STEAL.getIndex()] - prevTicks[CentralProcessor.TickType.STEAL.getIndex()];
        long cSys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()];
        long user = ticks[CentralProcessor.TickType.USER.getIndex()] - prevTicks[CentralProcessor.TickType.USER.getIndex()];
        long iowait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()];
        long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] - prevTicks[CentralProcessor.TickType.IDLE.getIndex()];
        long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;
        //cpu核數
        cpuInfo.put("cpuNum", processor.getLogicalProcessorCount());
        //cpu系統使用率
        cpuInfo.put("cSys", new DecimalFormat("#.##%").format(cSys * 1.0 / totalCpu));
        //cpu使用者使用率
        cpuInfo.put("user", new DecimalFormat("#.##%").format(user * 1.0 / totalCpu));
        //cpu當前等待率
        cpuInfo.put("iowait", new DecimalFormat("#.##%").format(iowait * 1.0 / totalCpu));
        //cpu當前使用率
        cpuInfo.put("idle", new DecimalFormat("#.##%").format(1.0 - (idle * 1.0 / totalCpu)));

        //cpu當前溫度
        cpuInfo.put("temp",hardware.getSensors().getCpuTemperature());


        return cpuInfo;
    }

    /**
     * 系統jvm資訊
     */
    public static JSONObject getJvmInfo() {
        JSONObject cpuInfo = new JSONObject();
        Properties props = System.getProperties();
        Runtime runtime = Runtime.getRuntime();
        long jvmTotalMemoryByte = runtime.totalMemory();
        long freeMemoryByte = runtime.freeMemory();
        //jvm總記憶體
        cpuInfo.put("total", formatByte(runtime.totalMemory()));
        //空閒空間
        cpuInfo.put("free", formatByte(runtime.freeMemory()));
        //jvm最大可申請
        cpuInfo.put("max", formatByte(runtime.maxMemory()));
        //vm已使用記憶體
        cpuInfo.put("user", formatByte(jvmTotalMemoryByte - freeMemoryByte));
        //jvm記憶體使用率
        cpuInfo.put("usageRate", new DecimalFormat("#.##%").format((jvmTotalMemoryByte - freeMemoryByte) * 1.0 / jvmTotalMemoryByte));
        //jdk版本
        cpuInfo.put("jdkVersion", props.getProperty("java.version"));
        //jdk路徑
        cpuInfo.put("jdkHome", props.getProperty("java.home"));
        return cpuInfo;
    }

    /**
     * 系統記憶體資訊
     */
    public static JSONObject getMemInfo() {
        JSONObject cpuInfo = new JSONObject();
        GlobalMemory memory = systemInfo.getHardware().getMemory();
        //總記憶體
        long totalByte = memory.getTotal();
        //剩餘
        long acaliableByte = memory.getAvailable();
        //總記憶體
        cpuInfo.put("total", formatByte(totalByte));
        //使用
        cpuInfo.put("used", formatByte(totalByte - acaliableByte));
        //剩餘記憶體
        cpuInfo.put("free", formatByte(acaliableByte));
        //使用率
        cpuInfo.put("usageRate", new DecimalFormat("#.##%").format((totalByte - acaliableByte) * 1.0 / totalByte));
        return cpuInfo;
    }

    /**
     * 系統碟符資訊
     */
    public static JSONArray getSysFileInfo() {
        JSONObject cpuInfo;
        JSONArray sysFiles = new JSONArray();
        FileSystem fileSystem = operatingSystem.getFileSystem();
        List<OSFileStore> fsArray = fileSystem.getFileStores();
        for (OSFileStore fs : fsArray) {
            cpuInfo = new JSONObject();
            //碟符路徑
            cpuInfo.put("dirName", fs.getMount());
            //碟符型別
            cpuInfo.put("sysTypeName", fs.getType());
            //檔案型別
            cpuInfo.put("typeName", fs.getName());
            //總大小
            cpuInfo.put("total", formatByte(fs.getTotalSpace()));
            //剩餘大小
            cpuInfo.put("free", formatByte(fs.getUsableSpace()));
            //已經使用量
            cpuInfo.put("used", formatByte(fs.getTotalSpace() - fs.getUsableSpace()));
            if (fs.getTotalSpace() == 0) {
                //資源的使用率
                cpuInfo.put("usage", 0);
            } else {
                cpuInfo.put("usage",new DecimalFormat("#.##%").format((fs.getTotalSpace() - fs.getUsableSpace()) * 1.0 / fs.getTotalSpace()));
            }
            sysFiles.add(cpuInfo);
        }
        return sysFiles;
    }

    /**
     * 系統資訊
     */
    public static JSONObject getSysInfo() throws UnknownHostException {
        JSONObject cpuInfo = new JSONObject();
        Properties props = System.getProperties();
        //作業系統名
        cpuInfo.put("osName", props.getProperty("os.name"));
        //系統架構
        cpuInfo.put("osArch", props.getProperty("os.arch"));
        //伺服器名稱
        cpuInfo.put("computerName", InetAddress.getLocalHost().getHostName());
        //伺服器Ip
        cpuInfo.put("computerIp", InetAddress.getLocalHost().getHostAddress());
        //伺服器Mac地址
        cpuInfo.put("computerMac",getMacAddr());
        //專案路徑
        cpuInfo.put("userDir", props.getProperty("user.dir"));
        return cpuInfo;
    }

    /**
     * 獲取系統的Mac地址
     */
    public static String getMacAddr() throws UnknownHostException {
        String hostAddress = InetAddress.getLocalHost().getHostAddress();
        SystemInfo systemInfo = new SystemInfo();
        List<Object> list = new ArrayList<>();
        HardwareAbstractionLayer hardware = systemInfo.getHardware();
        List<NetworkIF> networkIFs = hardware.getNetworkIFs();
        to:for (NetworkIF networkIF : networkIFs) {
            String[] iPv4addr = networkIF.getIPv4addr();
            for (String s : iPv4addr) {
                if (hostAddress.equals(s)) {
                    list.add(networkIF);
                    break to;
                }
            }
        }
        NetworkIF networkIF = (NetworkIF) list.get(0);
        String macAddr = networkIF.getMacaddr();
        return macAddr;
    }

    /**
     * 所有系統資訊
     */
    public static JSONObject getInfo() throws UnknownHostException {
        JSONObject info = new JSONObject();
        info.put("cpuInfo", getCpuInfo());
        info.put("jvmInfo", getJvmInfo());
        info.put("memInfo", getMemInfo());
        info.put("sysInfo", getSysInfo());
        info.put("sysFileInfo", getSysFileInfo());
        return info;
    }

    /**
     * 單位轉換
     */
    private static String formatByte(long byteNumber) {
        //換算單位
        double FORMAT = 1024.0;
        double kbNumber = byteNumber / FORMAT;
        if (kbNumber < FORMAT) {
            return new DecimalFormat("#.##KB").format(kbNumber);
        }
        double mbNumber = kbNumber / FORMAT;
        if (mbNumber < FORMAT) {
            return new DecimalFormat("#.##MB").format(mbNumber);
        }
        double gbNumber = mbNumber / FORMAT;
        if (gbNumber < FORMAT) {
            return new DecimalFormat("#.##GB").format(gbNumber);
        }
        double tbNumber = gbNumber / FORMAT;
        return new DecimalFormat("#.##TB").format(tbNumber);
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章