@xtccc
2016-12-06T10:27:50.000000Z
字数 2116
阅读 2496
开发技巧
SIGAR提供了统一的API来监控以下资源:
SIGAR提供了对多种语言的支持,例如Java、Perl、Python、Ruby等。
请看 SIGAR Github项目
SIGAR在使用之前需要针对具体的平台进行构建,然后生成相应的文件后再使用。
下面展示怎样在CentOS 64bit平台上通过Java client来使用SIGAR对CPU进行监控。
首先下载SIGAR的git源码。
下载好了之后,进入bindings/java目录,然后运行命令:
$ ant
运行成功后,可以看到bindings/java目录下有如下的目录:
drwxr-xr-x 5 root root 4096 Dec 5 10:46 build
-rw-r--r-- 1 root root 17466 Dec 5 10:08 build.xml
drwxr-xr-x 2 root root 4096 Dec 5 16:10 examples
drwxr-xr-x 4 root root 4096 Dec 5 10:08 hyperic_jni
drwxr-xr-x 2 root root 4096 Dec 5 10:08 lib
drwxr-xr-x 4 root root 4096 Dec 5 10:46 sigar-bin
drwxr-xr-x 4 root root 4096 Dec 5 10:08 src
其中,sigar-bin/lib/sigar.jar就包含了SIGAR for Jave的实现代码,我们的Java程序只要在classpath中包含该JAR包就可以了。
在bindings/java/examples中是2个使用Java client的示例Java代码文件,我们在其中再增加一个Java文件:
// CpuList.java
import org.hyperic.sigar.*;
class CpuList {
public static void main(String[] args) throws
SigarException, InterruptedException {
Sigar sigar = new Sigar();
int i = 0 ;
while (true) {
i += 1;
if (i > 10)
return;
CpuPerc cpu = sigar.getCpuPerc();
System.out.println(cpu.toString());
Thread.sleep(3*1000);
}
}
}
该文件的目的实际上是每隔3秒打印出当前CPU的使用状况,连续打印10次后退出。
编译
在bindings/java目录下,执行命令:
$ javac -classpath sigar-bin/lib/sigar.jar:examples examples/CpuList.java
编译成功后,会生成文件examples/CpuList.class
运行
运行命令:
$ java -cp sigar-bin/lib/sigar.jar:examples CpuList
CPU states: 75.3% user, 0.0% system, 0.0% nice, 0.0% wait, 24.6% idle
CPU states: 75.3% user, 0.0% system, 0.0% nice, 0.0% wait, 24.5% idle
CPU states: 75.3% user, 0.0% system, 0.0% nice, 0.2% wait, 24.2% idle
CPU states: 75.3% user, 0.0% system, 0.0% nice, 0.0% wait, 24.6% idle
CPU states: 75.3% user, 0.0% system, 0.0% nice, 0.0% wait, 24.5% idle
CPU states: 75.4% user, 0.0% system, 0.0% nice, 0.0% wait, 24.4% idle
CPU states: 75.3% user, 0.0% system, 0.0% nice, 0.0% wait, 24.5% idle
CPU states: 75.4% user, 0.0% system, 0.0% nice, 0.0% wait, 24.4% idle
CPU states: 75.3% user, 0.0% system, 0.0% nice, 0.0% wait, 24.5% idle
CPU states: 75.2% user, 0.1% system, 0.0% nice, 0.0% wait, 24.5% idle
OK, 调用成功。
以上数据代表什么意义? 参考 UNDERSTANDING LINUX CPU STATS