使用Java代码获取服务器性能信息及局域网内主机名
程序员文章站
2024-03-07 22:12:15
最近做个项目,就是要取得cpu占有率等等的系统信息,一开始以为要用动态链接库了,但后来发现可以像下面这样做,不去调用jni,这样省去了很多看新技术的时间o(∩_∩)o......
最近做个项目,就是要取得cpu占有率等等的系统信息,一开始以为要用动态链接库了,但后来发现可以像下面这样做,不去调用jni,这样省去了很多看新技术的时间o(∩_∩)o...
在java中,可以获得总的物理内存、剩余的物理内存、已使用的物理内存等信息,下面例子可以取得这些信息,并且获得在windows下的内存使用率。
首先编写一个monitorinfobean类,用来装载监控的一些信息,包括物理内存、剩余的物理内存、已使用的物理内存、内存使用率等字段,该类的代码如下:
package com.amgkaka.performance; /** */ /** * 监视信息的javabean类. * @author amg * @version 1.0 * creation date: 2008-4-25 - 上午10:37:00 */ 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; 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; } }
接着编写一个获得当前的监控信息的接口,该类的代码如下所示:
package com.amgkaka.performance; /** */ /** * 获取系统信息的业务逻辑类接口. * @author amg * @version 1.0 * creation date: 2008-3-11 - 上午10:06:06 */ public interface imonitorservice { /** */ /** * 获得当前的监控对象. * @return 返回构造好的监控对象 * @throws exception * @author amgkaka * creation date: 2008-4-25 - 上午10:45:08 */ public monitorinfobean getmonitorinfobean() throws exception; }
该类的实现类monitorserviceimpl如下所示:
package com.amgkaka.performance; import java.io.inputstreamreader; import java.io.linenumberreader; import sun.management.managementfactory; import com.sun.management.operatingsystemmxbean; /** */ /** * 获取系统信息的业务逻辑实现类. * @author amg * @version 1.0 creation date: 2008-3-11 - 上午10:06:06 */ public class monitorserviceimpl implements imonitorservice { //可以设置长些,防止读到运行此次系统检查时的cpu占用率,就不准了 private static final int cputime = 5000 ; private static final int percent = 100 ; private static final int faultlength = 10 ; /** */ /** * 获得当前的监控对象. * @return 返回构造好的监控对象 * @throws exception * @author amg * creation date: 2008-4-25 - 上午10:45:08 */ public monitorinfobean getmonitorinfobean() throws exception { int kb = 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); return infobean; } /** */ /** * 获得cpu使用率. * @return 返回cpu使用率 * @author amg * creation date: 2008-4-25 - 下午06:05:11 */ 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 * @author amg * creation date: 2008-4-25 - 下午06:10:14 */ 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 ; } /** */ /** * 测试方法. * @param args * @throws exception * @author amg * creation date: 2008-4-30 - 下午04:47:29 */ public static void main(string[] args) throws exception { imonitorservice service = new monitorserviceimpl(); monitorinfobean monitorinfo = service.getmonitorinfobean(); system.out.println("cpu占有率=" + monitorinfo.getcpuratio()); system.out.println("可使用内存=" + monitorinfo.gettotalmemory()); system.out.println("剩余内存=" + monitorinfo.getfreememory()); system.out.println("最大可使用内存=" + monitorinfo.getmaxmemory()); system.out.println("操作系统=" + monitorinfo.getosname()); system.out.println("总的物理内存=" + monitorinfo.gettotalmemorysize() + "kb" ); system.out.println("剩余的物理内存=" + monitorinfo.getfreememory() + "kb" ); system.out.println("已使用的物理内存=" + monitorinfo.getusedmemory() + "kb" ); system.out.println("线程总数=" + monitorinfo.gettotalthread() + "kb" ); } }
该实现类中需要用到一个自己编写byte的工具类,该类的代码如下所示:
package com.amgkaka.performance; /** */ /** * byte操作类. * @author amg * @version 1.0 * creation date: 2008-4-30 - 下午04:57:23 */ public class bytes { /** */ /** * 由于string.substring对汉字处理存在问题(把一个汉字视为一个字节),因此在 * 包含汉字的字符串时存在隐患,现调整如下: * @param src 要截取的字符串 * @param start_idx 开始坐标(包括该坐标) * @param end_idx 截止坐标(包括该坐标) * @return */ 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; } }
运行下monitorbeanimpl类,读者将会看到当前的内存、cpu利用率等信息。
ps:得到局域网内所有主机名的方法
import java.net.inetaddress; import java.net.unknownhostexception; public class a { static public void main(string[] args) { try { //通过主机名称得到ip地址 inetaddress address = inetaddress.getbyname("192.168.9.148"); system.out.println("192.168.9.148"+": "+address.gethostaddress()); // 通过ip得到主机名称 string ips="192.168.9.",ip; inetaddress addip; for(int i=148;i<255;i++){ ip=ips+i; addip=inetaddress.getbyname(ip); system.out.println(ip+": "+addip.gethostname()); } } catch(unknownhostexception uhe) { system.err.println("unable to find: "+"192.168.9.148"); } } }