Java代码在Linux的性能测试与监控实操指南
一、测试策略与工具选型
二、微基准测试 JMH 快速上手
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.36</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.36</version>
<scope>provided</scope>
</dependency>
dependencies {
implementation 'org.openjdk.jmh:jmh-core:1.36'
annotationProcessor 'org.openjdk.jmh:jmh-generator-annprocess:1.36'
}
import org.openjdk.jmh.annotations.*;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Warmup(iterations = 3, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(1)
@State(Scope.Benchmark)
public class StringConcatBenchmark {
@Benchmark
public String testStringConcat() {
return "Hello" + "World";
}
public static void main(String[] args) throws Exception {
org.openjdk.jmh.Main.main(args);
}
}
mvn clean install 后执行 java -jar target/benchmarks.jar@Measurement(iterations=…, time=…) 或适当提高 @Fork 值以隔离干扰。三、负载与压力测试实操
bin/jmeter.shjmeter -n -t test_plan.jmx -l result.jtljmeter -g result.jtl -o report/./gatling.sh -s simulations.BasicSimulationresults/ 目录自动生成 HTML 报告,包含响应时间分布、百分位、吞吐量等k6 run --out influxdb=http://localhost:8086/k6 script.js四、运行时监控与瓶颈定位
jps、ps -ef | grep javajstat -gc <PID> 1000(每 1000 ms 刷新一次)jstack <PID> > threads.txtjmap -dump:format=b,file=heap.hprof <PID>,再用 VisualVM/MAT 分析java -XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints \
-XX:+FlightRecorder -XX:StartFlightRecording=duration=60s,filename=app.jfr \
-jar app.jar
使用 jmc 打开 app.jfr 分析方法采样、锁竞争、GC 事件等top/htop、iotop五、实践注意事项