如何在Karate框架性能测试后获取服务器CPU与内存使用率?
在Karate性能测试中捕获服务器CPU和内存使用率的方法
当然可以,以下是几种实用的实现方式:
1. 执行系统命令采集数据
直接通过Java调用系统命令获取服务器的CPU和内存状态,适合快速实现:
- Linux环境:用
top、vmstat、free等命令,比如:// 采集CPU使用率 Process cpuProcess = new ProcessBuilder("bash", "-c", "top -bn1 | grep 'Cpu(s)' | awk '{print $2}'").start(); String cpuUsage = new BufferedReader(new InputStreamReader(cpuProcess.getInputStream())).readLine(); // 采集内存使用率 Process memProcess = new ProcessBuilder("bash", "-c", "free | grep Mem | awk '{print $3/$2 * 100.0}'").start(); String memUsage = new BufferedReader(new InputStreamReader(memProcess.getInputStream())).readLine(); - Windows环境:用
tasklist、wmic命令,比如:
可以把这些逻辑封装成工具类,在Karate测试的Process cpuProcess = new ProcessBuilder("wmic", "cpu", "get", "loadpercentage").start(); String cpuUsage = new BufferedReader(new InputStreamReader(cpuProcess.getInputStream())).lines() .skip(1).findFirst().orElse("0").trim();BeforeSuite和AfterSuite钩子中调用,或者启动定时任务在测试期间周期性采集。
2. 使用Java系统监控库
借助成熟的Java库直接获取系统指标,无需解析命令输出:
- Oshi:一款跨平台的系统信息库,支持获取CPU、内存、磁盘等多种指标。
首先引入依赖(Maven):
然后编写采集代码:<dependency> <groupId>com.github.oshi</groupId> <artifactId>oshi-core</artifactId> <version>6.4.0</version> </dependency>
在Karate测试中,通过import oshi.SystemInfo; import oshi.hardware.CentralProcessor; import oshi.hardware.GlobalMemory; public class SystemMonitor { public static void collectMetrics() { SystemInfo si = new SystemInfo(); CentralProcessor cpu = si.getHardware().getProcessor(); GlobalMemory memory = si.getHardware().getMemory(); // CPU使用率(需要计算间隔) long[] prevTicks = cpu.getSystemCpuLoadTicks(); try { Thread.sleep(1000); } catch (InterruptedException e) {} double cpuUsage = cpu.getSystemCpuLoadBetweenTicks(prevTicks) * 100; // 内存使用率 double memUsage = (memory.getTotal() - memory.getAvailable()) * 100.0 / memory.getTotal(); System.out.printf("CPU使用率: %.2f%%, 内存使用率: %.2f%%%n", cpuUsage, memUsage); } }AfterSuite钩子调用这个方法,或者启动线程定时采集数据,最后汇总到测试报告。
3. 利用Karate钩子实现周期性监控
通过Karate的钩子机制,在测试期间持续采集数据:
import com.intuit.karate.junit5.Karate; import java.util.Timer; import java.util.TimerTask; public class PerformanceTest { private static Timer monitorTimer; @Karate.BeforeSuite public static void startMonitoring() { monitorTimer = new Timer(); // 每5秒采集一次 monitorTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { SystemMonitor.collectMetrics(); // 调用前面的采集方法 } }, 0, 5000); } @Karate.AfterSuite public static void stopMonitoring() { if (monitorTimer != null) { monitorTimer.cancel(); // 这里可以把采集到的数据写入文件或追加到Karate报告 } } @Karate.Test public Karate runTests() { return Karate.run("performance-tests").relativeTo(getClass()); } }
4. 对接现有监控系统API
如果你的服务器已经部署了Prometheus、Zabbix等监控工具,可以直接调用它们的API获取指定时间段的指标数据。比如Prometheus的查询API:
// 请求Prometheus获取测试期间的CPU使用率平均值 String promUrl = "http://your-prometheus-server:9090/api/v1/query_range?query=100 - (avg by (instance) (irate(node_cpu_seconds_total{mode='idle'}[1m])) * 100)&start=1690000000&end=1690003600&step=15s"; // 用Java HttpClient发送请求并解析JSON响应
内容的提问来源于stack exchange,提问作者naveenz
相关产品推荐
相关产品推荐

