最近在做一个Java web项目时,有监控服务器性能信息等的需求,比如cpu、mem、disk等使用信息,于是各种google,找到了Sigar这个工具。
简介
Sigar(System Information Gatherer And Reporter),开源的跨平台系统信息收集工具,C语言 实现,下载之后是个压缩包,保留好了下面各种用到。
使用
由于仅在Java 里用到了Sigar,这里也就只讲讲java项目里怎么去用它(其他我也不会(⊙﹏⊙))。
1、下载Sigar.jar
<dependency >
<groupId > org.fusesource</groupId >
<artifactId > sigar</artifactId >
<version > 1.6.4</version >
</dependency >
非Maven:直接拷贝下载压缩包中的Sigar.jar 和jfinal-1.9-bin.jar(PathKit类需要用到)到你的项目lib目录
2、添加Sigar 依赖的本地库文件
此处解释一下,与普通jar包不同,Sigar API还要依赖本地的库文件来进行工作,其中:
Windows下Sigar.jar 依赖:sigar-amd64-winnt.dll 或 sigar-x86-winnt.dll Linux 下Sigar.jar依赖:libsigar-amd64-linux.so 或 libsigar-x86-linux.so
Sigar 通过java.library.path
加载这些本地库文件,这些库文件同样可以在下载的压缩包中找到,官方给出的库文件更多,可以根据自己的跨平台需要选择。 Sigar这一点是非常蛋疼的,为了用几个API,每部署到一台电脑还要去折腾一遍库文件,想想就不能忍,还好发现了这篇博客 ,算是曲线救国,终于能比较嗨皮的用Sigar了! :-D ,下面是具体做法:
i 将依赖库文件拷贝至项目某一目录下,此处我拷贝至web项目中的 //WebRoot/files/sigar
目录下 ii 在项目中通过代码获取此路径并将其添加至 java.library.path
中,下面是部分代码:
public class SigarUtils {
public final static Sigar sigar = initSigar();
private static Sigar initSigar () {
try {
String file = Paths.get(PathKit.getWebRootPath(), "files" , "sigar" ,".sigar_shellrc" ).toString();
File classPath = new File(file).getParentFile();
String path = System.getProperty("java.library.path" );
String sigarLibPath = classPath.getCanonicalPath();
if (!path.contains(sigarLibPath)) {
if (isOSWin()) {
path += ";" + sigarLibPath;
} else {
path += ":" + sigarLibPath;
}
System.setProperty("java.library.path" , path);
}
return new Sigar();
} catch (Exception e) {
return null ;
}
}
public static boolean isOSWin (){
String OS = System.getProperty("os.name" ).toLowerCase();
if (OS.indexOf("win" ) >= 0 ) {
return true ;
} else return false ;
}
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
3、终于可以用了
经过比一般jar包复杂N倍的折腾,终于能够用起来了,不过,Sigar 的javaAPI真的是又直观有简单又好用又全面有木有!!! 下面举几个项目中用到的栗子,可能都算不到冰山一角:
Sigar sigar = SigarUtils.sigar;
double cpuUsedPerc = sigar.getCpuPerc().getCombined();
double memUsed = sigar.getMem().getActualUsed();
double memTotal = sigar.getMem().getTotal();
double memUsedPerc = sigar.getMem().getUsedPercent();
String memUsedStr = String.format("%.2f" , memUsed/1024 /1024 /1024 )+"GB" ;
String memTotalStr = String.format("%.2f" , memTotal/1024 /1024 /1024 )+"GB" ;
String memUsedPercStr = String.format("%.2f" , memUsedPerc)+" %" ;
double diskUsed = sigar.getFileSystemUsage(PathKit.getWebRootPath()).getUsed();
double diskTotal = sigar.getFileSystemUsage(PathKit.getWebRootPath()).getTotal();
double diskUsedPerc = sigar.getFileSystemUsage(PathKit.getWebRootPath()).getUsePercent();
String diskUsedStr = String.format("%.2f" , diskUsed/1024 /1024 )+"GB" ;
String diskTotalStr = String.format("%.2f" , diskTotal/1024 /1024 )+"GB" ;
String diskUsedPercStr = String.format("%.2f" , diskUsedPerc*100 )+" %" ;
String fqdn = sigar.getFQDN();
更多API使用参考压缩包中的doc(p.s. Sigar给的这个压缩包真是无所不包 ╮(╯_╰)╭)
The end