天天看點

擷取cpu、記憶體、磁盤的使用率

最近項目中要求檢測伺服器cpu、記憶體、磁盤進行預警,在網上搜了些資料,發現有很多都是對于windows,也有很多獲得的資料是不對的,下面是我整理後的代碼:

先定義bean對象

public class MonitorInfoBean {

    private long totalMemory;   

    private long freeMemory;   

    private long maxMemory;   

    private String osName;   

    private long totalMemorySize;   

    private long freePhysicalMemorySize;   

    private long usedMemory;   

    private int totalThread;   

    private double cpuRatio;   

    private double memoryRatio;

    private String diskRatio;

    public long getFreeMemory() {   

        return freeMemory;   

    }   

    public void setFreeMemory(long freeMemory) {   

        this.freeMemory = freeMemory;   

    }   

    public long getFreePhysicalMemorySize() {   

        return freePhysicalMemorySize;   

    }   

    public void setFreePhysicalMemorySize(long freePhysicalMemorySize) {   

        this.freePhysicalMemorySize = freePhysicalMemorySize;   

    }   

    public long getMaxMemory() {   

        return maxMemory;   

    }   

    public void setMaxMemory(long maxMemory) {   

        this.maxMemory = maxMemory;   

    }   

    public String getOsName() {   

        return osName;   

    }   

    public void setOsName(String osName) {   

        this.osName = osName;   

    }   

    public long getTotalMemory() {   

        return totalMemory;   

    }   

    public void setTotalMemory(long totalMemory) {   

        this.totalMemory = totalMemory;   

    }   

    public long getTotalMemorySize() {   

        return totalMemorySize;   

    }   

    public void setTotalMemorySize(long totalMemorySize) {   

        this.totalMemorySize = totalMemorySize;   

    }   

    public int getTotalThread() {   

        return totalThread;   

    }   

    public void setTotalThread(int totalThread) {   

        this.totalThread = totalThread;   

    }   

    public long getUsedMemory() {   

        return usedMemory;   

    }   

    public void setUsedMemory(long usedMemory) {   

        this.usedMemory = usedMemory;   

    }   

    public double getCpuRatio() {   

        return cpuRatio;   

    }   

    public void setCpuRatio(double cpuRatio) {   

        this.cpuRatio = cpuRatio;   

    }

    public double getMemoryRatio() {

        return memoryRatio;

    }

    public void setMemoryRatio(double memoryRatio) {

        this.memoryRatio = memoryRatio;

    }

    public String getDiskRatio() {

        return diskRatio;

    }

    public void setDiskRatio(String diskRatio) {

        this.diskRatio = diskRatio;

    }   

}

實作類定義:

import java.io.BufferedReader;

import java.io.File;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.LineNumberReader;

import java.lang.management.ManagementFactory;

import java.text.DecimalFormat;

import java.util.StringTokenizer;

import com.sun.management.OperatingSystemMXBean;

import com.pkit.netmgr.model.Bytes;

import com.pkit.netmgr.model.MonitorInfoBean;

public class MonitorServiceImpl {

     private static final int CPUTIME = 30;   

        private static final int PERCENT = 100;   

        private static final int FAULTLENGTH = 10;   

        public MonitorInfoBean Diskfree() {

                File[] roots = File.listRoots();

                String diskRatio="";

                // 擷取磁盤分區清單

                for (File file : roots){

                    long freespace = file.getFreeSpace();

                    long totalSpace=  file.getTotalSpace();

                    if(totalSpace>0){

                        double disk =(Double) (1 - freespace * 1.0

                                    / totalSpace) * 100;

                        DecimalFormat df = new DecimalFormat("#.00");

                        diskRatio = diskRatio+"|"+SafeUtil.getString(df.format(disk));

                    }    

                }

                MonitorInfoBean bean = new MonitorInfoBean();

                bean.setDiskRatio(diskRatio);

                return bean;

        }

        public MonitorInfoBean getMonitorInfoBeanCpu() throws Exception {   

            int kb = 1024;   

            // 作業系統   

            String osName = System.getProperty("os.name");    

            double cpuRatio = 0;   

            if (osName.toLowerCase().startsWith("windows")) {   

                cpuRatio = this.getCpuRatioForWindows();   

            }   

            else {

               cpuRatio = this.getCpuRateForLinux();

               DecimalFormat df = new DecimalFormat("#.00");

               cpuRatio = SafeUtil.getDouble(df.format(cpuRatio));

               System.out.println("cpuRatio="+cpuRatio);

            }   

            // 構造傳回對象   

            MonitorInfoBean infoBean = new MonitorInfoBean();   

            infoBean.setCpuRatio(cpuRatio);   

            return infoBean;   

        }   

        public MonitorInfoBean getMonitorInfoBeanMemory() throws Exception {   

            int kb = 1024;   

            // 可使用記憶體   

            long totalMemory = Runtime.getRuntime().totalMemory();   

            // 剩餘記憶體   

            long freeMemory = Runtime.getRuntime().freeMemory();   

            // 最大可使用記憶體   

            long maxMemory = Runtime.getRuntime().maxMemory() / kb/kb;   

            OperatingSystemMXBean osmxb = (OperatingSystemMXBean)sun.management.ManagementFactory   

                    .getOperatingSystemMXBean();   

            // 作業系統   

            String osName = System.getProperty("os.name");   

            // 總的實體記憶體   

            long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb/kb;   

            // 已使用的實體記憶體   

            long usedMemory = (osmxb.getTotalPhysicalMemorySize() - osmxb   

                    .getFreePhysicalMemorySize())   

                    / kb/ kb;   

            // 獲得線程總數   

            ThreadGroup parentThread;   

            for (parentThread = Thread.currentThread().getThreadGroup(); parentThread   

                    .getParent() != null; parentThread = parentThread.getParent())   

                ;   

            int totalThread = parentThread.activeCount();   

            Double compare=0.0;

            if (osName.toLowerCase().startsWith("windows")) {   

                // 總的實體記憶體+虛拟記憶體

                long totalvirtualMemory = osmxb.getTotalSwapSpaceSize();

                // 剩餘的實體記憶體

                long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize();

                compare = (Double) (1 - freePhysicalMemorySize * 1.0

                  / totalvirtualMemory) * 100;

                DecimalFormat df = new DecimalFormat("#.00");

                compare = SafeUtil.getDouble(df.format(compare));

            }   

            else {

                compare = getMemoryRatioForLinux();

                DecimalFormat df = new DecimalFormat("#.00");

                compare = SafeUtil.getDouble(df.format(compare*100));

            }

            // 構造傳回對象   

            MonitorInfoBean infoBean = new MonitorInfoBean();   

            infoBean.setFreeMemory(freeMemory);   

            infoBean.setMaxMemory(maxMemory);   

            infoBean.setOsName(osName);   

            infoBean.setTotalMemory(totalMemory);   

            infoBean.setTotalMemorySize(totalMemorySize);   

            infoBean.setTotalThread(totalThread);

            infoBean.setUsedMemory(usedMemory);  

            infoBean.setMemoryRatio(compare);

            return infoBean;

        }

      private double getCpuRateForLinux(){   

            InputStream is = null;   

            InputStreamReader isr = null;   

            BufferedReader brStat = null;   

            StringTokenizer tokenStat = null;   

            try{   

                Process process = Runtime.getRuntime().exec("top -b -n 1");

                is = process.getInputStream();                     

                isr = new InputStreamReader(is);   

                brStat = new BufferedReader(isr);   

                    brStat.readLine();   

                    brStat.readLine();

                    tokenStat = new StringTokenizer(brStat.readLine());

                    tokenStat.nextToken();   

                    tokenStat.nextToken();   

                    tokenStat.nextToken();   

                    tokenStat.nextToken();   

                    String cpuUsage = tokenStat.nextToken();   

                    System.out.println("CPU idle : "+cpuUsage);   

                    Float usage = new Float(cpuUsage.substring(0,cpuUsage.indexOf("%")));   

                    return (100-usage.floatValue());   

            } catch(IOException ioe){   

                System.out.println(ioe.getMessage());

                freeResource(is, isr, brStat);   

                return 1;   

            } finally{   

                freeResource(is, isr, brStat);   

            }   

        }   

        private static void freeResource(InputStream is, InputStreamReader isr, BufferedReader br){   

            try{   

                if(is!=null)   

                    is.close();   

                if(isr!=null)   

                    isr.close();   

                if(br!=null)   

                    br.close();   

            }catch(IOException ioe){   

                System.out.println(ioe.getMessage());   

            }   

        }   

        private double getCpuRatioForWindows() {   

            try {   

                String procCmd = System.getenv("windir")   

                        + "\\system32\\wbem\\wmic.exe process get Caption,CommandLine,"   

                        + "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";   

                // 取程序資訊   

                long[] c0 = readCpu(Runtime.getRuntime().exec(procCmd));   

                Thread.sleep(CPUTIME);   

                long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd));   

                if (c0 != null && c1 != null) {   

                    long idletime = c1[0] - c0[0];   

                    long busytime = c1[1] - c0[1];   

                    return Double.valueOf(   

                            PERCENT * (busytime) / (busytime + idletime))   

                            .doubleValue();   

                } else {   

                    return 0.0;   

                }   

            } catch (Exception ex) {   

                ex.printStackTrace();   

                return 0.0;   

            }   

        }   

        private long[] readCpu(final Process proc) {   

            long[] retn = new long[2];   

            try {   

                proc.getOutputStream().close();   

                InputStreamReader ir = new InputStreamReader(proc.getInputStream());   

                LineNumberReader input = new LineNumberReader(ir);   

                String line = input.readLine();   

                if (line == null || line.length() <FAULTLENGTH) {   

                    return null;   

                }   

                int capidx = line.indexOf("Caption");   

                int cmdidx = line.indexOf("CommandLine");   

                int rocidx = line.indexOf("ReadOperationCount");   

                int umtidx = line.indexOf("UserModeTime");   

                int kmtidx = line.indexOf("KernelModeTime");   

                int wocidx = line.indexOf("WriteOperationCount");   

                long idletime = 0;   

                long kneltime = 0;   

                long usertime = 0;   

                while ((line = input.readLine()) != null) {   

                    if (line.length()< wocidx) {   

                        continue;   

                    }   

                    // 字段出現順序:Caption,CommandLine,KernelModeTime,ReadOperationCount,   

                    // ThreadCount,UserModeTime,WriteOperation   

                    String caption = Bytes.substring(line, capidx, cmdidx - 1)   

                            .trim();   

                    String cmd = Bytes.substring(line, cmdidx, kmtidx - 1).trim();   

                    if (cmd.indexOf("wmic.exe") >= 0) {   

                        continue;   

                    }   

                    // log.info("line="+line);   

                    if (caption.equals("System Idle Process")   

                            || caption.equals("System")) {   

                        idletime += Long.valueOf(   

                                Bytes.substring(line, kmtidx, rocidx - 1).trim())   

                                .longValue();   

                        idletime += Long.valueOf(   

                                Bytes.substring(line, umtidx, wocidx - 1).trim())   

                                .longValue();   

                        continue;   

                    }   

                    kneltime += Long.valueOf(   

                            Bytes.substring(line, kmtidx, rocidx - 1).trim())   

                            .longValue();   

                    usertime += Long.valueOf(   

                            Bytes.substring(line, umtidx, wocidx - 1).trim())   

                            .longValue();   

                }   

                retn[0] = idletime;   

                retn[1] = kneltime + usertime;   

                return retn;   

            } catch (Exception ex) {   

                ex.printStackTrace();   

            } finally {   

                try {   

                    proc.getInputStream().close();   

                } catch (Exception e) {   

                    e.printStackTrace();   

                }   

            }   

            return null;   

        }   

     public double getMemoryRatioForLinux() {  

            double memUsage = 0.0;  

            Process pro = null;  

            Runtime r = Runtime.getRuntime();  

            try {  

                String command = "cat /proc/meminfo";  

                pro = r.exec(command);  

                BufferedReader in = new BufferedReader(new InputStreamReader(pro.getInputStream()));  

                String line = null;  

                int count = 0;  

                long totalMem = 0, freeMem = 0;  

                while((line=in.readLine()) != null){      

                    String[] memInfo = line.split("\\s+");  

                    if(memInfo[0].startsWith("MemTotal")){  

                        totalMem = Long.parseLong(memInfo[1]);  

                    }  

                    if(memInfo[0].startsWith("MemFree")){  

                        freeMem = Long.parseLong(memInfo[1]);  

                    }  

                    memUsage = 1- (float)freeMem/(float)totalMem;

                    System.out.println("記憶體totalMem="+totalMem+",freeMem="+freeMem);

                    if(++count == 2){  

                        break;  

                    }                 

                }  

                in.close();  

                pro.destroy();  

            } catch (IOException e) {  

                e.printStackTrace();  

            }     

            return memUsage;  

        }  

}   

public class Bytes {   

    public static String substring(String src, int start_idx, int end_idx){   

        byte[] b = src.getBytes();   

        String tgt = "";   

        for(int i=start_idx; i<=end_idx; i++){   

            tgt +=(char)b[i];   

        }   

        return tgt;   

    }