求可跨平台且容器感知的Java进程CPU使用率获取库
符合需求的Java库推荐:Oshi
是的,存在满足你需求的Java库——Oshi,它完全适配你的核心要求:
- 跨平台支持:原生兼容Mac、Linux、Windows三大操作系统,无需手写不同平台的适配代码
- 容器感知能力:能够自动识别容器环境(如Docker、Kubernetes容器),读取容器的CPU配额限制(比如你提到的每周期1000 ticks),计算进程CPU使用率时会基于容器的限制值,而非宿主机的CPU资源
- 进程CPU使用率计算:可以获取指定进程(包括当前JVM进程)任意时间段内的CPU使用率,通过两次采样CPU时间戳的差值计算,精度可控
简单使用示例
下面是获取当前JVM进程最近2秒CPU使用率的代码:
import oshi.SystemInfo; import oshi.hardware.CentralProcessor; import oshi.software.os.OSProcess; import oshi.software.os.OperatingSystem; import java.util.List; import java.util.concurrent.TimeUnit; public class ContainerAwareCpuMonitor { public static void main(String[] args) throws InterruptedException { SystemInfo systemInfo = new SystemInfo(); OperatingSystem os = systemInfo.getOperatingSystem(); CentralProcessor processor = systemInfo.getHardware().getProcessor(); // 获取当前JVM进程ID long currentPid = ProcessHandle.current().pid(); OSProcess currentProcess = os.getProcesses().stream() .filter(p -> p.getProcessID() == currentPid) .findFirst() .orElseThrow(() -> new IllegalStateException("无法找到当前进程")); // 第一次采样CPU时间 long prevTotalTicks = currentProcess.getKernelModeTime() + currentProcess.getUserModeTime(); // 等待2秒 TimeUnit.SECONDS.sleep(2); // 第二次采样CPU时间 long currTotalTicks = currentProcess.getKernelModeTime() + currentProcess.getUserModeTime(); // 获取容器CPU限制(如果处于容器环境) long cpuQuota = processor.getProcessorIdentifier().getCpuQuota(); long cpuPeriod = processor.getProcessorIdentifier().getCpuPeriod(); double cpuLimit = cpuQuota > 0 ? (double) cpuQuota / cpuPeriod : processor.getLogicalProcessorCount(); // 计算CPU使用率 double usedTicks = currTotalTicks - prevTotalTicks; double timeIntervalMs = TimeUnit.SECONDS.toMillis(2); // 转换为百分比,基于CPU限制计算 double cpuUsage = (usedTicks / (timeIntervalMs * 1000)) / cpuLimit * 100; System.out.printf("当前进程最近2秒CPU使用率: %.2f%%%n", cpuUsage); } }
依赖引入
如果使用Maven,在pom.xml中添加:
<dependency> <groupId>com.github.oshi</groupId> <artifactId>oshi-core</artifactId> <version>6.4.0</version> <!-- 建议使用最新稳定版本 --> </dependency>
补充说明
- Oshi在Linux容器中会自动读取
/sys/fs/cgroup/cpu下的配额文件,在Mac/Windows容器中也有对应的适配逻辑,无需手动处理容器环境的检测 - 除了当前进程,你也可以通过进程ID获取任意进程的CPU使用率数据
内容的提问来源于stack exchange,提问作者Gilgamesz
相关产品推荐
相关产品推荐

