/**
* 获取 CPU.
*
* @return
*/
public static double getCpuPercent() {
OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
String osJson = JSONObject.toJSONString(operatingSystemMXBean);
JSONObject jsonObject = JSONObject.parseObject(osJson);
double processCpuLoad = jsonObject.getDouble("processCpuLoad") * 100;
double systemCpuLoad = jsonObject.getDouble("systemCpuLoad") * 100;
Long totalPhysicalMemorySize = jsonObject.getLong("totalPhysicalMemorySize");
Long freePhysicalMemorySize = jsonObject.getLong("freePhysicalMemorySize");
double totalMemory = 1.0 * totalPhysicalMemorySize;
double freeMemory = 1.0 * freePhysicalMemorySize;
double memoryUseRatio = 1.0 * (totalPhysicalMemorySize - freePhysicalMemorySize) / totalPhysicalMemorySize
* 100;
return systemCpuLoad;
}
/**
* 获取 MEM.
*
* @return
*/
public static double getMemPercent() {
OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
String osJson = JSONObject.toJSONString(operatingSystemMXBean);
JSONObject jsonObject = JSONObject.parseObject(osJson);
Long totalPhysicalMemorySize = jsonObject.getLong("totalPhysicalMemorySize");
Long freePhysicalMemorySize = jsonObject.getLong("freePhysicalMemorySize");
// 获取缓存和缓冲区大小
long buffers = 0L;
long cached = 0L;
try {
Process process = Runtime.getRuntime().exec("free -m");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith("Mem:")) {
String[] parts = line.split("\\s+");
buffers = Long.parseLong(parts[5]) * 1024 * 1024; // 转换为字节
cached = Long.parseLong(parts[6]) * 1024 * 1024; // 转换为字节
break;
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
double totalMemory = 1.0 * totalPhysicalMemorySize;
double actualFreeMemory = 1.0 * (freePhysicalMemorySize + buffers + cached);
double usedMemory = totalMemory - actualFreeMemory;
double memoryUseRatio = (usedMemory / totalMemory) * 100;
return memoryUseRatio;
}
/**
* 获取 DISK.
*
* @return
*/
public static double getDiskPercent() {
double diskPercent = 0;
// TODO: 看哪个?给配置,或全返回 结构,由使用者判断.
try {
FileSystem fs = FileSystems.getDefault();
for (FileStore store : fs.getFileStores()) {
String name = store.name();
long usableSpace = store.getUsableSpace();
long totalSpace = store.getTotalSpace();
long freeSpace = store.getUnallocatedSpace();
double usageRate = (double) (totalSpace - freeSpace) / totalSpace * 100;
diskPercent = diskPercent == 0 ? usageRate : diskPercent;
LOGGER.info("name : [{}]", new Object[] { name });
LOGGER.info("usableSpace : [{}]", new Object[] { usableSpace });
LOGGER.info("totalSpace : [{}]", new Object[] { totalSpace });
LOGGER.info("freeSpace : [{}]", new Object[] { freeSpace });
LOGGER.info("usageRate : [{}]", new Object[] { String.format("%.2f", usageRate) });
}
} catch (IOException e) {
e.printStackTrace();
}
return diskPercent;
}
03-13