系統內存硬盤cpu數據獲取

package com.tod.bim.monitoring.util;

import org.hyperic.sigar.*;

/**
 * @author zj
 * @version 1.0
 * @functin
 * @date 2020/5/19 16:41
 */
public class SystemMonitoryUtils {
    /**
     * cpu情況
     *
     * @return [空閒率,使用率]
     * @throws SigarException
     */
    public static Double[] cpu() throws SigarException {
        Sigar sigar = new Sigar();

        CpuPerc[] cpuList = sigar.getCpuPercList();
        double idles = 0;
        double combined = 0;
        int length = cpuList.length;
        for (int i = 0; i < cpuList.length; i++) {// 不管是單塊CPU還是多CPU都適用
            CpuPerc cpu = cpuList[i];
            idles += cpu.getIdle();
            combined += cpu.getCombined();
        }

        return new Double[]{idles / length, combined / length};
    }

    /**
     * 內存情況
     *
     * @return [內存剩餘量,內存使用量]
     * @throws SigarException
     */
    public static Double[] momery() throws SigarException {
        Sigar sigar = new Sigar();
        Mem mem = sigar.getMem();

        Double[] momerys = {
                mem.getFree() / 1024D / 1024 / 1024,
                mem.getUsed() / 1024D / 1024 / 1024
        };

        return momerys;
    }

    /**
     * 硬盤情況
     * @return [硬盤剩餘量,硬盤使用量]
     * @throws Exception
     */
    public static Double[] disk() throws Exception {
        Sigar sigar = new Sigar();
        FileSystem fslist[] = sigar.getFileSystemList();
        double total = 0;
        double free = 0;
        double avai = 0;
        double used = 0;
        double usePercent = 0;

        for (int i = 0; i < fslist.length; i++) {
            FileSystem fs = fslist[i];
            FileSystemUsage usage = sigar.getFileSystemUsage(fs.getDirName());
            switch (fs.getType()) {
                case 0: // TYPE_UNKNOWN :未知
                    break;
                case 1: // TYPE_NONE
                    break;
                case 2: // TYPE_LOCAL_DISK : 本地硬盤
                    //total += (usage.getTotal() / 1024D / 1024);
                    free += usage.getFree() / 1024D / 1024;
                    //avai += usage.getAvail() / 1024D / 1024;
                    used += usage.getUsed() / 1024D / 1024;
                    //usePercent += usage.getUsePercent();
                    break;
                case 3:// TYPE_NETWORK :網絡
                    break;
                case 4:// TYPE_RAM_DISK :閃存
                    break;
                case 5:// TYPE_CDROM :光驅
                    break;
                case 6:// TYPE_SWAP :頁面交換
                    break;
            }
        }
        return new Double[]{free,used};
    }

}

 

maven依賴

    <dependency>
            <groupId>org.fusesource</groupId>
            <artifactId>sigar</artifactId>
            <version>1.6.4</version>
    </dependency>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章