java Operating SystemMXBenはサーバーjvmの負荷情報を取得して、データの変換が異常です.


javaライブラリのOperating SystemMXBern類を使ってサーバー負荷に関する情報を取得し、NumberFormatException異常を報告します.
プロジェクトはサーバーの状態を監視する必要があります.javaが持参したOperatingSystemMXBenでサーバーの負荷情報を取得します.原文:http://kakaluyi.javaeye.com/blog/211492 まず、物理メモリ、残りの物理メモリ、使用済みの物理メモリ、メモリ使用率などのフィールドを含めて監視するためのMonitoInfoBenクラスを作成します.このクラスのコードは以下の通りです.
import java.util.List;
    /** 
     *      JavaBean . 
     */
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 String time;

    private int totalProcess;

    private List processDetail;

    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 int getTotalProcess() {
        return totalProcess;
    }

    public void setTotalProcess(int totalProcess) {
        this.totalProcess = totalProcess;
    }

    public List getProcessDetail() {
        return processDetail;
    }

    public void setProcessDetail(List processDetail) {
        this.processDetail = processDetail;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

}
次に、現在の監視情報を得るためのインターフェースを作成します.このクラスのコードは以下の通りです.
import com.datanew.dto.MonitorInfoBean;
import com.datanew.service.MonitorService;
import com.sun.management.OperatingSystemMXBean;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.management.ManagementFactory;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("MonitorService")
public class MonitorServiceImpl implements MonitorService {
    //      ,              cpu   ,    
    private static final int CPUTIME = 5000;

    private static final int PERCENT = 100;

    private static final int FAULTLENGTH = 10;

 		/** 
         *   String.subString         (           ),     
         *              ,     :  
         * @param src          
         * @param start_idx     (     )  
         * @param end_idx       (     )  
         * @return  
         */  
    private static String byteSubstring(String src, int start_idx, int end_idx) {
        byte[] b = src.getBytes();
        StringBuffer tgt = new StringBuffer();
        for (int i = start_idx; i <= end_idx; i++) {
            tgt.append((char) b[i]);
        }
        return tgt.toString();
    }

    //             .
    public MonitorInfoBean getMonitorInfoBean() throws IOException {
        int kb = 1024 * 1024;
        //      
        long totalMemory = Runtime.getRuntime().totalMemory() / kb;
        //     
        long freeMemory = Runtime.getRuntime().freeMemory() / kb;
        //        
        long maxMemory = Runtime.getRuntime().maxMemory() / kb;
        OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
        //     
        String osName = System.getProperty("os.name");
        //       
        long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb;
        //        
        long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize() / kb;
        //         
        long usedMemory = (osmxb.getTotalPhysicalMemorySize() - osmxb.getFreePhysicalMemorySize()) / kb;
        //       
        ThreadGroup parentThread;
        for (parentThread = Thread.currentThread().getThreadGroup(); parentThread.getParent() != null; parentThread = parentThread.getParent())
            ;
        int totalThread = parentThread.activeCount();
        double cpuRatio = 0;
        if (osName.toLowerCase().startsWith("windows")) {
            cpuRatio = this.getCpuRatioForWindows();
        }
        MonitorInfoBean infoBean = new MonitorInfoBean();
        infoBean.setFreeMemory(freeMemory);
        infoBean.setFreePhysicalMemorySize(freePhysicalMemorySize);
        infoBean.setMaxMemory(maxMemory);
        infoBean.setOsName(osName);
        infoBean.setTotalMemory(totalMemory);
        infoBean.setTotalMemorySize(totalMemorySize);
        infoBean.setTotalThread(totalThread);
        infoBean.setUsedMemory(usedMemory);
        infoBean.setCpuRatio(cpuRatio);
        Process process = Runtime.getRuntime().exec("cmd.exe /c tasklist");
        BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        StringBuilder sb = new StringBuilder();
        int i = -2;
        List l = new ArrayList<>();
        while ((line = input.readLine()) != null) {
            if (line.length() > 0) {
                i++;
                if (i > 0) {
                    Map m = new HashMap<>();
                    m.put("name", line.substring(0, 25).trim());
                    m.put("pid", line.substring(26, 34).trim());
                    m.put("memUsage", line.substring(64).trim().split(" ")[0]);
                    l.add(m);
                }
            }
        }
        input.close();
        infoBean.setTotalProcess(i);
        infoBean.setProcessDetail(l);
        infoBean.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        return infoBean;
    }

    //      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) (PERCENT * (busytime) / (busytime + idletime));
            } else {
                return 0.0;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return 0.0;
        }
    }

    //      CPU  
    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 = byteSubstring(line, capidx, cmdidx - 1).trim();
                String cmd = byteSubstring(line, cmdidx, kmtidx - 1).trim();
                if (cmd.contains("wmic.exe")) {
                    continue;
                }
                
                if (caption.equals("System Idle Process") || caption.equals("System")) {
                    idletime += Long.valueOf(byteSubstring(line, kmtidx, rocidx - 1).trim());
                    idletime += Long.valueOf(byteSubstring(line, umtidx, wocidx - 1).trim());
                    continue;
                }

                kneltime += Long.valueOf(byteSubstring(line, kmtidx, rocidx - 1).trim());
                usertime += Long.valueOf(byteSubstring(line, umtidx, wocidx - 1).trim());

            }
            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 static void main(String[] args) throws Exception {
        MonitorInfoBean monitorInfo = new MonitorServiceImpl().getMonitorInfoBean();
        System.out.println(monitorInfo.getProcessDetail());
        System.out.println("cpu   =" + monitorInfo.getCpuRatio());
        System.out.println("      =" + monitorInfo.getTotalMemorySize() + "MB");
        System.out.println("        =" + monitorInfo.getUsedMemory() + "MB");
        System.out.println("    =" + monitorInfo.getTotalProcess());
    }
上のコードはピットがあります.テストコードがava.lang.Number FormatExceptionを投げる可能性があります.For input string:異常です.debug後、エンコーディングセットの問題でストリームを取得する際にエンコーディングセットが設定されていないことが分かりました.
InputStream Reader ir=new InputStream Reader(proc.get Input Stream);
byteSubstringメソッドを実行する時、中国語で表示される可能性がある時は?文字列を切り取る際の切り取りが不正確です.変更後のコード:
 //      CPU  
    private long[] readCpu(final Process proc) {
        long[] retn = new long[2];
        try {
            proc.getOutputStream().close();
             InputStreamReader ir = null;
            //            
            String str = System.getProperty("sun.jnu.encoding");
	        if ("GBK".equals(str)){
				ir = new InputStreamReader(proc.getInputStream(),"gbk");
	        }else if ("UTF-8".equals(str)){
				ir = new InputStreamReader(proc.getInputStream(),"utf-8");
	        }
           
            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 = byteSubstring(line, capidx, cmdidx - 1).trim();
                String cmd = byteSubstring(line, cmdidx, kmtidx - 1).trim();
                if (cmd.contains("wmic.exe")) {
                    continue;
                }
                
                if (caption.equals("System Idle Process") || caption.equals("System")) {
                    idletime += Long.valueOf(byteSubstring(line, kmtidx, rocidx - 1).trim());
                    idletime += Long.valueOf(byteSubstring(line, umtidx, wocidx - 1).trim());
                    continue;
                }

                kneltime += Long.valueOf(byteSubstring(line, kmtidx, rocidx - 1).trim());
                usertime += Long.valueOf(byteSubstring(line, umtidx, wocidx - 1).trim());

            }
            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;
    }
あとでテストすれば大丈夫です.しかし、プロジェクトテストの時に、もう一つの問題が見つかりました.tomcatで運行しても大丈夫です.でもwebsphere 7で運行している時にコードが届きます.
OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
このステップは聞き分けました.異常はありませんでした.