用java获取并传出虚拟机系统实时性能参数(1:得到性能参数)

准备构建一个日志系统,记录创建的虚拟机的实时性能参数。首先先要获取系统的性能参数,再将参数发送给服务器端存储下来。


首先是搜了一个内存参数的代码(跨平台可用),略微修改,用的jre6:


import java.io.*;
import com.sun.management.OperatingSystemMXBean;
import java.lang.management.ManagementFactory;
public class Tst{
       public static String pt="D:\\abc.txt";
       public Tst(){
       }
       public static void main(String[] args) throws Exception{
              //free和use和total均为KB
              long free=0;
              long use=0;
              long total=0;
              int kb=1024;
              Runtime rt=Runtime.getRuntime();
              total=rt.totalMemory();
              free=rt.freeMemory();
              use=total-free;
              System.out.println("系统内存已用的空间为:"+use/kb+"MB");
              System.out.println("系统内存的空闲空间为:"+free/kb+"MB");
              System.out.println("系统总内存空间为:"+total/kb+"MB");
              OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
              long physicalFree=osmxb.getFreePhysicalMemorySize()/kb;
              long physicalTotal=osmxb.getTotalPhysicalMemorySize()/kb;
              long physicalUse=physicalTotal-physicalFree;
              String os=System.getProperty("os.name");
              System.out.println("操作系统的版本:"+os);
              System.out.println("系统物理内存已用的空间为:"+physicalFree+"MB");
              System.out.println("系统物理内存的空闲空间为:"+physicalUse+"MB");
              System.out.println("总物理内存:"+physicalTotal+"MB");
       // 获得线程总数
       ThreadGroup parentThread;
        for(parentThread = Thread.currentThread().getThreadGroup(); parentThread
                .getParent() != null; parentThread= parentThread.getParent())
            ;
        int totalThread = parentThread.activeCount();
       System.out.println("获得线程总数:"+totalThread);
       }    
}

有可能会遇到Access restriction: The type OperatingSystemMXBean is not accessible due to restriction on required library C:\Program Files

 \Java\jre7\lib\rt.jar,不让用OperatingSystemMXBean,这个是eclipse限制的(我不知道为什么不让访问这个包,望高手指出),可以在它的设置里面修改。


Windows -> Preferences -> Java -> Compiler -> Errors/Warnings
Project -> Properties -> Java Compiler -> Errors/Warnings

Locate the "Forbidden reference (access rules)" option under "Deprecated and restricted API" section in the dialog box. This option decides how to handle access rules defined inside Eclipse. By default it is set to "Error" which causes Eclipse to complain about references to any restricted classes. Choosing any other option (Warning or Ignore) will remove these error messages.


对于要得到准确的CPU参数,就要麻烦一些,这里我们只考虑linux。注意到linux里有top命令类似于window的任务管理器,而 top -b -n 1 能获得静态的信息。考虑java执行脚本来获得该信息。

参考网上代码写一个工具类如下:

package bupt.tx.systemmonitor;

//for Linux

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class MySystemMonitor {
	public static double getCpuUsage() throws Exception {
		double cpuUsed = 0;
		double idleUsed = 0.0;
		Runtime rt = Runtime.getRuntime();
		Process p = rt.exec("top -b -n 1");// call "top" command in Linux
		BufferedReader in = null;
		
		try {
			in = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String str = null;
			int linecount = 0;
			while ((str = in.readLine()) != null) {
				linecount++;
				if (linecount == 3) {
					String[] s = str.split("%");
					String idlestr = s[3];
					String idlestr1[] = idlestr.split(" ");
					idleUsed = Double.parseDouble(idlestr1[idlestr1.length - 1]);
					cpuUsed = 100 - idleUsed;

					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			in.close();
		}

		return cpuUsed;
	}

	public static double getMemUsage() throws Exception {
		long memUsed = 0;
		long memTotal = 0;
		double memUsage = 0.0;
		Runtime rt = Runtime.getRuntime();
		Process p = rt.exec("top -b -n 1");// call "top" command in Linux
		BufferedReader in = null;
		
		try {
			in = new BufferedReader(new InputStreamReader(p.getInputStream()));

			String str = null;
			int linecount = 0;
			while ((str = in.readLine()) != null) {
				linecount++;
				if (linecount == 4) {
					String[] s = str.split("k ");
					String memUsedstr = s[1];
					String memTotalstr = s[0];
					String memUsedstr1[] = memUsedstr.split(" ");
					memUsed = Long.parseLong(memUsedstr1[memUsedstr1.length - 1]);
					String memTotalstr1[] = memTotalstr.split(" ");
					memTotal = Long.parseLong(memTotalstr1[memTotalstr1.length - 1]);					
					memUsage = memUsed * 100 / memTotal;

					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			in.close();
		}

		return memUsage;
	}

	public static String getTotalInfo() throws Exception {
		String info = "";
		Runtime rt = Runtime.getRuntime();
		Process p = rt.exec("top -b -n 1");// call "top" command in Linux
		BufferedReader in = null;

		try {
			in = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String str = null;
			int linecount = 0;
			while (++linecount <= 5 && ( str = in.readLine() ) != null) {
				str += "\n";
				info += str;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			in.close();
		}

		return info;
	}
}

做一下测试:

package bupt.tx.systemmonitor;

public class test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try
		{
		  System.out.println(MySystemMonitor.getCpuUsage());
		  System.out.println(MySystemMonitor.getMemUsage());
		  System.out.println(MySystemMonitor.getTotalInfo());
		}
		catch(Exception e)
		{
		  e.printStackTrace();
		}
	}

}

在ubuntu10.10中测试运行可以得到正确结果。


你可能感兴趣的:(日志系统)