java 獲取內(nèi)存 cpu 磁盤的使用情況

問題描述

目前線上的服務(wù)越來越多,需要監(jiān)控對(duì)應(yīng)服務(wù)的運(yùn)行狀態(tài)和系統(tǒng)基本信息:磁盤,cpu,內(nèi)存的使用情況,線上服務(wù)和本地環(huán)境的機(jī)器類型不同,查找相關(guān)資料未找到可用的代碼,經(jīng)過查找相關(guān)資料,整理如下。

使用oshi

1.需要導(dǎo)入的包

<!--系統(tǒng)使用率導(dǎo)包開始-->
       <dependency>  <!--工具類 小數(shù)格式化 可以改為其他-->
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>4.0.9</version>
        </dependency>
        <dependency>
            <groupId>net.java.dev.jna</groupId>
            <artifactId>jna</artifactId>
            <version>4.5.0</version>
        </dependency>
        <dependency>
            <groupId>net.java.dev.jna</groupId>
            <artifactId>jna-platform</artifactId>
            <version>4.5.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.github.oshi/oshi-json -->
        <dependency>
            <groupId>com.github.oshi</groupId>
            <artifactId>oshi-json</artifactId>
            <version>3.6.1</version>
        </dependency>
        <!--系統(tǒng)使用率導(dǎo)包結(jié)束-->

2.上干活 具體代碼

這里獲取磁盤使用情況在linux下有問題,所以使用了其他的方式獲取

import java.io.InputStreamReader;
import java.io.LineNumberReader;

import cn.hutool.core.util.NumberUtil;
import lombok.extern.slf4j.Slf4j;
import oshi.json.SystemInfo;
import oshi.json.hardware.CentralProcessor;
import oshi.json.hardware.GlobalMemory;
import oshi.json.hardware.HWDiskStore;
import oshi.json.hardware.HardwareAbstractionLayer;

/**
 * <p>
 * 類說明
 * </p>
 *
 * @author Shawn
 * @since 2018/06/29
 */
@Slf4j
public class SystemUsageUtil {

    private static SystemInfo systemInfo = new SystemInfo();

    /**
     * 獲取內(nèi)存的使用率
     *
     * @return 內(nèi)存使用率 0.36
     */
    public static double getMemoryUsage() {
        HardwareAbstractionLayer hal = systemInfo.getHardware();
        GlobalMemory memory = hal.getMemory();
        long available = memory.getAvailable();
        long total = memory.getTotal();
        log.info("getMemoryUsage available={},total={}", available, total);
        double useRate = NumberUtil.div(available, total, 2);
        return useRate;
    }

    /**
     * 獲取CPU的使用率
     *
     * @return CPU使用率 0.36
     */
    public static double getCpuUsage() {
        HardwareAbstractionLayer hal = systemInfo.getHardware();
        CentralProcessor processor = hal.getProcessor();
        double useRate = processor.getSystemCpuLoadBetweenTicks();
        log.info("getCpuUsage useRate={}", useRate);
        return NumberUtil.div(useRate, 1, 2);
    }

    /**
     * 獲取磁盤的使用率
     *
     * @return CPU使用率 0.36
     */
    public static double getDiskUsage() {
        if (isWindows()) {
            return getWinDiskUsage();
        }
        return getUnixDiskUsage();
    }


    /**
     * 判斷系統(tǒng)是否為windows
     *
     * @return 是否
     */
    private static boolean isWindows() {
        return System.getProperties().getProperty("os.name").toUpperCase().contains("WINDOWS");
    }

    /**
     * 獲取linux 磁盤使用率
     *
     * @return 磁盤使用率
     */
    private static double getUnixDiskUsage() {
        String ioCmdStr = "df -h /";
        String resultInfo = runCommand(ioCmdStr);
        String[] data = resultInfo.split(" +");
        double total = Double.parseDouble(data[10].replace("%", ""));
        return total / 100;
    }

    /**
     * 獲取linux 磁盤使用率
     *
     * @return 磁盤使用率
     */
    private static double getWinDiskUsage() {

        HardwareAbstractionLayer hal = systemInfo.getHardware();
        HWDiskStore[] diskStores = hal.getDiskStores();
        long total = 0;
        long used = 0;
        if (diskStores != null && diskStores.length > 0) {
            for (HWDiskStore diskStore : diskStores) {
                long size = diskStore.getSize();
                long writeBytes = diskStore.getWriteBytes();
                total += size;
                used += writeBytes;
            }
        }
        return NumberUtil.div(used, total, 2);
    }


    /**
     * 執(zhí)行系統(tǒng)命令
     *
     * @param CMD 命令
     * @return 字符串結(jié)果
     */
    private static String runCommand(String CMD) {
        StringBuilder info = new StringBuilder();
        try {
            Process pos = Runtime.getRuntime().exec(CMD);
            pos.waitFor();
            InputStreamReader isr = new InputStreamReader(pos.getInputStream());
            LineNumberReader lnr = new LineNumberReader(isr);
            String line;
            while ((line = lnr.readLine()) != null) {
                info.append(line).append("\n");
            }
        } catch (Exception e) {
            info = new StringBuilder(e.toString());
        }
        return info.toString();
    }
}

親測(cè) linux和windows環(huán)境可正常使用

參考資料

https://github.com/oshi/oshi

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 關(guān)于Mongodb的全面總結(jié) MongoDB的內(nèi)部構(gòu)造《MongoDB The Definitive Guide》...
    中v中閱讀 32,295評(píng)論 2 89
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,008評(píng)論 25 709
  • 一天轉(zhuǎn)戰(zhàn)四個(gè)場(chǎng)地,工作加學(xué)習(xí),披星戴月走回家??粗鴿M屏的圣誕慶?;顒?dòng),我只想啃個(gè)蘋果,看個(gè)電視劇。 感謝伙伴們的禮物。
    Anne_GG閱讀 109評(píng)論 0 0
  • 怎么說,今天發(fā)生的一幕讓我覺得異常難過。 因?yàn)橄掠晏?,我閑來無聊,盯著窗子外面,看淅淅瀝瀝的雨下個(gè)不停,不經(jīng)意間看...
    松下的瑜閱讀 319評(píng)論 3 5
  • washingaway閱讀 158評(píng)論 0 0

友情鏈接更多精彩內(nèi)容