刚开始想到的是使用网上开源的sigar.jar来做:最后同事提醒我该工具已经很久没有更新了,踌躇再三,决定使用网上的一些其他的方法:
sigar.jar的方法实现(类似的方法网上实现有很多):
package com.utils;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.hyperic.sigar.FileSystem;
import org.hyperic.sigar.FileSystemUsage;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import com.caller.bean.basic.CpuInfo;
import com.caller.bean.basic.DiskInfoBean;
import com.caller.bean.basic.MemoryUsageBean;
import com.google.common.collect.Lists;
import com.service.MonitorException;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
* SIGAR监控框架,需要配合一些dll文件,so文件等本地动态链接库、支持库一同使用
* Represents the resource manager service imp.
*
*/
@Deprecated // Sigar缺乏维护
public class ResourceManagerSigarUtils {
/** The millseconds. */
private static final int MILLSECONDS = 1000;
/** The sigar. */
private static final Sigar SIGAR = new Sigar();
/**
* Gets the disk infos.
*
* @return the disk infos
*/
public static Collection<DiskInfoBean> getDiskInfo() {
try {
FileSystem[] fsArray = SIGAR.getFileSystemList();
Collection<DiskInfoBean> diskInfoBeans = Lists.newArrayList();
for (FileSystem fs : fsArray) {
if (fs.getType() != FileSystem.TYPE_LOCAL_DISK) {
continue;
}
FileSystemUsage fileSystemUsage;
fileSystemUsage = SIGAR.getFileSystemUsage(fs.getDirName());
DiskInfoBean diskInfoBean = new DiskInfoBean();
diskInfoBean.setTotalSize(String.valueOf(fileSystemUsage.getTotal()));
diskInfoBean.setUsedSize(String.valueOf(fileSystemUsage.getUsed()));
diskInfoBean.setAvailablePercentage(String.valueOf(1 - fileSystemUsage.getUsePercent()));
diskInfoBean.setDrive(fs.getDirName());
diskInfoBeans.add(diskInfoBean);
}
return diskInfoBeans;
}
catch (SigarException e) {
throw new MonitorException("Could not get DiskInfos", e);
}
}
/**
* Gets the cpu infos.
*
* @return the cpu infos
*/
public static CpuInfo getCpuInfo() {
try {
CpuInfo cpuInfo = new CpuInfo();
cpuInfo.setFrequency(SIGAR.getCpuInfoList()[0].getMhz() + "MHz");
cpuInfo.setCoreCount(SIGAR.getCpuInfoList().length);
Double[] utlizations = getCpuUtilzation();
cpuInfo.setMaxUtilization(utlizations[2].intValue());
cpuInfo.setMedianUtilization(utlizations[1].intValue());
cpuInfo.setAverageUtilization(utlizations[3].intValue());
cpuInfo.setModel(SIGAR.getCpuInfoList()[0].getModel());
return cpuInfo;
}
catch (SigarException e) {
throw new MonitorException("Could not get Cpu info", e);
}
}
/**
* Gets the memory usage info.
*
* @return the memory usage info
*/
public static MemoryUsageBean getMemoryUsageInfo() {
try {
MemoryUsageBean memoryUsageBean = new MemoryUsageBean();
Mem mem;
mem = SIGAR.getMem();
memoryUsageBean.setTotalSize(mem.getTotal());
memoryUsageBean.setUsedSize(mem.getUsed());
Double percent = mem.getFreePercent() * 100;
memoryUsageBean.setAvailablePercentage(percent.intValue());
return memoryUsageBean;
}
catch (SigarException e) {
throw new MonitorException("Could not get memory Information", e);
}
}
/**
* Gets the cpu utilzation.
*
* @return the cpu utilzation
*/
private static Double[] getCpuUtilzation() {
try {
List<Double> utlizations = Lists.newArrayList();
Double sum = 0.0;
for (int i = 0; i < 9; i++) {
Double utilize;
utilize = SIGAR.getCpuPerc().getSys();
sum += utilize;
utlizations.add(utilize);
Thread.sleep(MILLSECONDS);
}
Double average = sum / 9;
Collections.sort(utlizations);
return (Double[]) Arrays.asList(utlizations.get(0), utlizations.get(4), utlizations.get(8), average).toArray();
}
catch (Exception e) {
throw new MonitorException("Could not get cpu utilization", e);
}
}
/**
* The main method.
*
* @param args
* the arguments
*/
public static void main(String[] args) {
Collection<DiskInfoBean> diskInfoBeans = getDiskInfo();
System.out.println(JSONArray.fromObject(diskInfoBeans).toString());
MemoryUsageBean memoryUsageBean = getMemoryUsageInfo();
System.out.println(JSONObject.fromObject(memoryUsageBean).toString());
CpuInfo cpuInfo = getCpuInfo();
System.out.println(JSONObject.fromObject(cpuInfo).toString());
}
}
笔者很希望能够在网上找到开源的一些东西能够如jar包之类的东西,同事笑称,如果是Google开源的那当然没问题,在github上面搜了很多,一些工具和java相关的jar包确实有,但是维护的人不多,有维护的人多的,可惜不是java的,现在给大家介绍一些
工具1:oshi
工具2:jhardware
工具3:psutil
工具4:osquery
后面两个工具看起来很不错的样子,非常想使用,可惜是Python的,又不想在代码里面嵌套Python的东西也不想安装osquery这么高级的玩意,psutil是一个跨平台的系统监控的工具包,Cross-platform lib for process and system monitoring in Python.,osquery也挺有意思的一个东西,应该也很好用的。有兴趣大家一起学习一下。
在网上找了一些简单的实现,系统本身的业务对于这些的需求不是很大。于是在保留了原有的sigar的实现后,添加了如下实现
package com.utils;
import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.util.Collection;
import com.caller.bean.basic.CpuInfo;
import com.caller.bean.basic.DiskInfoBean;
import com.caller.bean.basic.MemoryUsageBean;
import com.google.common.collect.Lists;
import com.sun.management.OperatingSystemMXBean;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class ResourceManagerUtils {
public static CpuInfo getCpuInfo() {
String os = System.getProperty("os.name").toLowerCase();
if (os.indexOf("windows") >= 0) {
return WindowsInfoUtils.getCpuInfo();
}
// TODO 其他系统
return null;
}
public static Collection<DiskInfoBean> getDiskInfo() {
File[] files = File.listRoots();
Collection<DiskInfoBean> diskInfoBeans = Lists.newArrayList();
for (File file : files) {
if (file.isDirectory()) {
DiskInfoBean diskInfoBean = new DiskInfoBean();
diskInfoBean.setDrive(file.getPath());
diskInfoBean.setTotalSize(String.valueOf(file.getTotalSpace()));
diskInfoBean.setUsedSize(String.valueOf(file.getTotalSpace() - file.getUsableSpace()));
diskInfoBean.setAvailablePercentage(String.valueOf((double) file.getUsableSpace() / (double) file.getTotalSpace()));
diskInfoBeans.add(diskInfoBean);
}
}
return diskInfoBeans;
}
public static MemoryUsageBean getMemoryUsageInfo() {
OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
MemoryUsageBean memoryUsageBean = new MemoryUsageBean();
memoryUsageBean.setTotalSize(operatingSystemMXBean.getTotalPhysicalMemorySize());
memoryUsageBean.setUsedSize(operatingSystemMXBean.getTotalPhysicalMemorySize() - operatingSystemMXBean.getFreePhysicalMemorySize());
Integer percent = (int) (operatingSystemMXBean.getFreePhysicalMemorySize() * 100 / operatingSystemMXBean.getTotalPhysicalMemorySize());
memoryUsageBean.setAvailablePercentage(percent);
return memoryUsageBean;
}
public static void main(String[] args) throws IOException {
Collection<DiskInfoBean> diskInfoBeans = getDiskInfo();
CpuInfo cpuInfo = getCpuInfo();
MemoryUsageBean memoryUsageBean = getMemoryUsageInfo();
System.out.println(JSONObject.fromObject(memoryUsageBean));
System.out.println(JSONObject.fromObject(cpuInfo));
System.out.println(JSONArray.fromObject(diskInfoBeans));
}
}
package com.utils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import com.caller.bean.basic.CpuInfo;
import com.service.MonitorException;
/**
* Represents the windows info utils.
*/
public class WindowsInfoUtils {
/** The default pause time. */
private final static int DEFAULT_PAUSE_TIME = 1000;
/**
* Gets the cpu info.
*
* @return the cpu info
*/
public static CpuInfo getCpuInfo() {
try {
String cpuInfoCommand = "cmd /c wmic cpu get Name,NumberOfCores,MaxClockSpeed /value";
Process process = Runtime.getRuntime().exec(cpuInfoCommand);
Properties properties = new Properties();
properties.load(process.getInputStream());
CpuInfo cpuInfo = new CpuInfo();
cpuInfo.setCoreCount(Integer.parseInt(properties.getProperty("NumberOfCores")));
cpuInfo.setFrequency(properties.getProperty("MaxClockSpeed"));
cpuInfo.setModel(properties.getProperty("Name"));
List<Integer> loadpercentages = getLoadPercentage();
cpuInfo.setMaxUtilization(loadpercentages.get(2));
cpuInfo.setMedianUtilization(loadpercentages.get(1));
cpuInfo.setAverageUtilization(loadpercentages.get(3));
return cpuInfo;
}
catch (Exception e) {
throw new MonitorException("Could not get Cpu information", e);
}
}
/**
* Gets the load percentage.
*
* @return the load percentage
*/
private static List<Integer> getLoadPercentage() {
try {
List<Integer> list = new ArrayList<>();
int sum = 0;
String getcpuLoadPercentageCommand = "cmd /c wmic cpu get LoadPercentage /value";
for (int i = 0; i < 9; i++) {
Process process = Runtime.getRuntime().exec(getcpuLoadPercentageCommand);
Properties properties = new Properties();
properties.load(process.getInputStream());
Integer loadpercentage = Integer.parseInt(properties.getProperty("LoadPercentage"));
sum += loadpercentage;
list.add(loadpercentage);
Thread.sleep(DEFAULT_PAUSE_TIME);
}
Collections.sort(list);
int average = sum / 9;
return Arrays.asList(list.get(0), list.get(4), list.get(8), average);
}
catch (Exception e) {
throw new MonitorException("Could not get Cpu load percentage", e);
}
}
}
让我们来了解一下wmic这个cmd的指令吧:关于wmic这个命令是啥玩意,请百度吧