思路:java执行脚本,拿到返回值,读取返回值,再对返回值进行分析获取想要的值。
传统的jdk查询系统信息不适用,要么是误差大,要么是难以实现。
//代码运行到linux上
//获取 disk使用情况 单位Byte
public static Map<String, Object> getDiskStatus() {
Map<String, Object> diskMap = new LinkedHashMap<>();
long total = 0;
try {
//java执行脚本
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("df -k");
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String str = null;
String[] strArray = null;
int line = 0;
// 一行行读
while ((str = in.readLine()) != null) {
line++;
// 跳过第一行
if (line == 1) {
continue;
}
int m = 0;
// 一行以空格分开
strArray = str.split(" ");
// 行的遍历
for (String para : strArray) {
// 去掉空格的长度==0表示该位置为空
if (para.trim().length() == 0) {
continue;
}
++m;
// 第2列
if (m == 2) {
Long dataCap = Long.valueOf(para) * 1024;
total += dataCap;
String mounted = strArray[strArray.length - 1];
if ("/data".equals(mounted)) {
// 数据分区大小
diskMap.put("disk_data", dataCap);
}
}
if (m == 5) {
// 如果该字符串以%
if (para.endsWith("%")) {
String mounted = strArray[strArray.length - 1];
if ("/data".equals(mounted)) {
// 去掉%
String s = para.replace("%", "");
Float percent = Float.valueOf(s);
// 数据分区已使用率
diskMap.put("percent", percent);
}
}
}
}
}
diskMap.put("total", Long.valueOf(objectFormat(total)));
} catch (Exception e) {
LOG.error(e.getMessage());
} finally {
in.close();
}
} catch (Exception e) {
LOG.error(e.getMessage());
}
return diskMap;
}
//查询内存占比
public static Map<String, Float> getMemeryStatus() {
Map<String, Float> map = new HashMap(10);
// 从bit转成gb
float constm = 1024 * 1024 * 1024;
// 已使用的内存大小
float usedPhysicalMemorySize = Float.parseFloat(objectFormat(getUsedPhysicalMemorySize() / constm));
// 总共的内存大小
float totalPhysicalMemorySize = Float.parseFloat(objectFormat(getTotalPhysicalMemorySize() / constm));
float percent = Float.parseFloat(objectFormat((usedPhysicalMemorySize / totalPhysicalMemorySize * 100)));
map.put("total", totalPhysicalMemorySize);
map.put("use", usedPhysicalMemorySize);
map.put("percent", percent);
return map;
}
//查询cpu
public static float getCpuPercent() throws IOException, BashException {
Runtime runtime = Runtime.getRuntime();
// 执行top命令,top是动态的,我们只要一次结果
Process top = runtime.exec("top -b -n 1");
BufferedReader buf = new BufferedReader(new InputStreamReader(top.getInputStream()));
String str = "";
float percent = 0;
int line = 0;
// 一行一行读
while ((str = buf.readLine()) != null) {
// 跳过第一和第二行
line++;
if (line == 1 || line == 2) {
continue;
}
// 切割
String[] split = str.split(" ");
int length = split.length;
percent = Float.parseFloat(split[length - 2]);
break;
}
return percent;
}