簡單的java獲取系統的參數

剛開始想到的是使用網上開源的sigar.jar來做:最後同事提醒我該工具已經很久沒有更新了,躊躇再三,決定使用網上的一些其他的方法:

sigar.jar的方法實現(類似的方法網上實現有很多):

package com.utils;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.hyperic.sigar.FileSystem;
import org.hyperic.sigar.FileSystemUsage;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;

import com.caller.bean.basic.CpuInfo;
import com.caller.bean.basic.DiskInfoBean;
import com.caller.bean.basic.MemoryUsageBean;
import com.google.common.collect.Lists;
import com.service.MonitorException;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * SIGAR監控框架,需要配合一些dll文件,so文件等本地動態鏈接庫、支持庫一同使用
 * Represents the resource manager service imp.
 *
 */
@Deprecated // Sigar缺乏維護
public class ResourceManagerSigarUtils {

    /** The millseconds. */
    private static final int MILLSECONDS = 1000;

    /** The sigar. */
    private static final Sigar SIGAR = new Sigar();

    /**
     * Gets the disk infos.
     *
     * @return the disk infos
     */
    public static Collection<DiskInfoBean> getDiskInfo() {
        try {
            FileSystem[] fsArray = SIGAR.getFileSystemList();
            Collection<DiskInfoBean> diskInfoBeans = Lists.newArrayList();
            for (FileSystem fs : fsArray) {
                if (fs.getType() != FileSystem.TYPE_LOCAL_DISK) {
                    continue;
                }
                FileSystemUsage fileSystemUsage;
                fileSystemUsage = SIGAR.getFileSystemUsage(fs.getDirName());
                DiskInfoBean diskInfoBean = new DiskInfoBean();
                diskInfoBean.setTotalSize(String.valueOf(fileSystemUsage.getTotal()));
                diskInfoBean.setUsedSize(String.valueOf(fileSystemUsage.getUsed()));
                diskInfoBean.setAvailablePercentage(String.valueOf(1 - fileSystemUsage.getUsePercent()));
                diskInfoBean.setDrive(fs.getDirName());
                diskInfoBeans.add(diskInfoBean);
            }
            return diskInfoBeans;
        }
        catch (SigarException e) {
            throw new MonitorException("Could not get DiskInfos", e);
        }
    }

    /**
     * Gets the cpu infos.
     *
     * @return the cpu infos
     */
    public static CpuInfo getCpuInfo() {
        try {
            CpuInfo cpuInfo = new CpuInfo();
            cpuInfo.setFrequency(SIGAR.getCpuInfoList()[0].getMhz() + "MHz");
            cpuInfo.setCoreCount(SIGAR.getCpuInfoList().length);
            Double[] utlizations = getCpuUtilzation();
            cpuInfo.setMaxUtilization(utlizations[2].intValue());
            cpuInfo.setMedianUtilization(utlizations[1].intValue());
            cpuInfo.setAverageUtilization(utlizations[3].intValue());
            cpuInfo.setModel(SIGAR.getCpuInfoList()[0].getModel());
            return cpuInfo;
        }
        catch (SigarException e) {
            throw new MonitorException("Could not get Cpu info", e);
        }
    }

    /**
     * Gets the memory usage info.
     *
     * @return the memory usage info
     */
    public static MemoryUsageBean getMemoryUsageInfo() {
        try {
            MemoryUsageBean memoryUsageBean = new MemoryUsageBean();
            Mem mem;
            mem = SIGAR.getMem();
            memoryUsageBean.setTotalSize(mem.getTotal());
            memoryUsageBean.setUsedSize(mem.getUsed());
            Double percent = mem.getFreePercent() * 100;
            memoryUsageBean.setAvailablePercentage(percent.intValue());
            return memoryUsageBean;
        }
        catch (SigarException e) {
            throw new MonitorException("Could not get memory Information", e);
        }
    }

    /**
     * Gets the cpu utilzation.
     *
     * @return the cpu utilzation
     */
    private static Double[] getCpuUtilzation() {
        try {
            List<Double> utlizations = Lists.newArrayList();
            Double sum = 0.0;
            for (int i = 0; i < 9; i++) {
                Double utilize;

                utilize = SIGAR.getCpuPerc().getSys();
                sum += utilize;
                utlizations.add(utilize);
                Thread.sleep(MILLSECONDS);
            }
            Double average = sum / 9;
            Collections.sort(utlizations);
            return (Double[]) Arrays.asList(utlizations.get(0), utlizations.get(4), utlizations.get(8), average).toArray();
        }
        catch (Exception e) {
            throw new MonitorException("Could not get cpu utilization", e);
        }
    }

    /**
     * The main method.
     *
     * @param args
     *            the arguments
     */
    public static void main(String[] args) {
        Collection<DiskInfoBean> diskInfoBeans = getDiskInfo();
        System.out.println(JSONArray.fromObject(diskInfoBeans).toString());
        MemoryUsageBean memoryUsageBean = getMemoryUsageInfo();
        System.out.println(JSONObject.fromObject(memoryUsageBean).toString());
        CpuInfo cpuInfo = getCpuInfo();
        System.out.println(JSONObject.fromObject(cpuInfo).toString());
    }
}

筆者很希望能夠在網上找到開源的一些東西能夠如jar包之類的東西,同事笑稱,如果是Google開源的那當然沒問題,在github上面搜了很多,一些工具和java相關的jar包確實有,但是維護的人不多,有維護的人多的,可惜不是java的,現在給大家介紹一些

工具1:oshi

工具2:jhardware

工具3:psutil

工具4:osquery

後面兩個工具看起來很不錯的樣子,非常想使用,可惜是Python的,又不想在代碼裏面嵌套Python的東西也不想安裝osquery這麼高級的玩意,psutil是一個跨平臺的系統監控的工具包,Cross-platform lib for process and system monitoring in Python.,osquery也挺有意思的一個東西,應該也很好用的。有興趣大家一起學習一下。

在網上找了一些簡單的實現,系統本身的業務對於這些的需求不是很大。於是在保留了原有的sigar的實現後,添加了如下實現

package com.utils;

import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.util.Collection;

import com.caller.bean.basic.CpuInfo;
import com.caller.bean.basic.DiskInfoBean;
import com.caller.bean.basic.MemoryUsageBean;
import com.google.common.collect.Lists;
import com.sun.management.OperatingSystemMXBean;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class ResourceManagerUtils {

    public static CpuInfo getCpuInfo() {
        String os = System.getProperty("os.name").toLowerCase();
        if (os.indexOf("windows") >= 0) {
            return WindowsInfoUtils.getCpuInfo();
        }
        // TODO 其他系統
        return null;
    }

    public static Collection<DiskInfoBean> getDiskInfo() {
        File[] files = File.listRoots();
        Collection<DiskInfoBean> diskInfoBeans = Lists.newArrayList();
        for (File file : files) {
            if (file.isDirectory()) {
                DiskInfoBean diskInfoBean = new DiskInfoBean();
                diskInfoBean.setDrive(file.getPath());
                diskInfoBean.setTotalSize(String.valueOf(file.getTotalSpace()));
                diskInfoBean.setUsedSize(String.valueOf(file.getTotalSpace() - file.getUsableSpace()));
                diskInfoBean.setAvailablePercentage(String.valueOf((double) file.getUsableSpace() / (double) file.getTotalSpace()));
                diskInfoBeans.add(diskInfoBean);
            }
        }
        return diskInfoBeans;
    }

    public static MemoryUsageBean getMemoryUsageInfo() {
        OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
        MemoryUsageBean memoryUsageBean = new MemoryUsageBean();
        memoryUsageBean.setTotalSize(operatingSystemMXBean.getTotalPhysicalMemorySize());
        memoryUsageBean.setUsedSize(operatingSystemMXBean.getTotalPhysicalMemorySize() - operatingSystemMXBean.getFreePhysicalMemorySize());
        Integer percent = (int) (operatingSystemMXBean.getFreePhysicalMemorySize() * 100 / operatingSystemMXBean.getTotalPhysicalMemorySize());
        memoryUsageBean.setAvailablePercentage(percent);
        return memoryUsageBean;
    }

    public static void main(String[] args) throws IOException {
        Collection<DiskInfoBean> diskInfoBeans = getDiskInfo();
        CpuInfo cpuInfo = getCpuInfo();
        MemoryUsageBean memoryUsageBean = getMemoryUsageInfo();
        System.out.println(JSONObject.fromObject(memoryUsageBean));
        System.out.println(JSONObject.fromObject(cpuInfo));
        System.out.println(JSONArray.fromObject(diskInfoBeans));
    }
}
package com.utils;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Properties;


import com.caller.bean.basic.CpuInfo;
import com.service.MonitorException;


/**
 * Represents the windows info utils.
 */
public class WindowsInfoUtils {


    /** The default pause time. */
    private final static int DEFAULT_PAUSE_TIME = 1000;


    /**
     * Gets the cpu info.
     *
     * @return the cpu info
     */
    public static CpuInfo getCpuInfo() {
        try {
            String cpuInfoCommand = "cmd /c wmic cpu get Name,NumberOfCores,MaxClockSpeed /value";
            Process process = Runtime.getRuntime().exec(cpuInfoCommand);
            Properties properties = new Properties();
            properties.load(process.getInputStream());
            CpuInfo cpuInfo = new CpuInfo();
            cpuInfo.setCoreCount(Integer.parseInt(properties.getProperty("NumberOfCores")));
            cpuInfo.setFrequency(properties.getProperty("MaxClockSpeed"));
            cpuInfo.setModel(properties.getProperty("Name"));
            List<Integer> loadpercentages = getLoadPercentage();
            cpuInfo.setMaxUtilization(loadpercentages.get(2));
            cpuInfo.setMedianUtilization(loadpercentages.get(1));
            cpuInfo.setAverageUtilization(loadpercentages.get(3));
            return cpuInfo;
        }
        catch (Exception e) {
            throw new MonitorException("Could not get Cpu information", e);
        }
    }


    /**
     * Gets the load percentage.
     *
     * @return the load percentage
     */
    private static List<Integer> getLoadPercentage() {


        try {
            List<Integer> list = new ArrayList<>();
            int sum = 0;
            String getcpuLoadPercentageCommand = "cmd /c wmic cpu get LoadPercentage /value";
            for (int i = 0; i < 9; i++) {
                Process process = Runtime.getRuntime().exec(getcpuLoadPercentageCommand);
                Properties properties = new Properties();
                properties.load(process.getInputStream());
                Integer loadpercentage = Integer.parseInt(properties.getProperty("LoadPercentage"));
                sum += loadpercentage;
                list.add(loadpercentage);
                Thread.sleep(DEFAULT_PAUSE_TIME);
            }
            Collections.sort(list);
            int average = sum / 9;
            return Arrays.asList(list.get(0), list.get(4), list.get(8), average);
        }
        catch (Exception e) {
            throw new MonitorException("Could not get Cpu load percentage", e);
        }
    }
}

讓我們來了解一下wmic這個cmd的指令吧:關於wmic這個命令是啥玩意,請百度吧








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