获取cpu、内存、磁盘的使用率

来源:互联网 发布:查询数据库所有表 编辑:程序博客网 时间:2024/06/10 01:43

最近项目中要求检测服务器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;   
     
    /** cpu使用率. */   
    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;
        }
        /**  
         * 获得cpu使用率.  
         * @return 返回构造好的监控对象  
         * @throws Exception 
         */   
        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;   
        }   
        
        
        /**  
         * 获得当前的监控对象.  
         * @return 返回构造好的监控对象  
         * @throws Exception 
         */   
        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());   
            }   
        }   
      
      
        /**  
         * 获得CPU使用率.  
         * @return 返回cpu使用率  
         */   
        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;   
            }   
        }   
      
        /**       
    
    * 读取CPU信息.  
         * @param proc  
         * @return 
         */   
        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;   
    }  








原创粉丝点击