Skip to main content
 首页 » 编程设计

SpringBoot集成JMH

2022年07月18日25qq78292959

第一步:添加依赖:

<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.19</version>
<scope>provided</scope>
</dependency>

第二步:创建类:
/** 
 * @desc: 
 * @author: 毛会懂 
 * @create: 2021-11-16 13:32:00 
 **/ 
@BenchmarkMode(Mode.AverageTime) 
@OutputTimeUnit(TimeUnit.MILLISECONDS) 
@Warmup(iterations = 5,time = 1,timeUnit = TimeUnit.SECONDS) 
@Measurement(iterations = 5,time = 1,timeUnit = TimeUnit.SECONDS) 
@Fork(1) 
@State(Scope.Benchmark) 
public class JMHFirstBenchmark { 
 
    private BarrageService barrageService; 
 
    @Setup(Level.Trial) 
    public void setUp(){ 
        // 启动应用程序 
        ConfigurableApplicationContext run = SpringApplication.run(xxxxApplicationBootstrap.class); 
        // 从spring中拿Bean 
        barrageService = run.getBean(BarrageService.class); 
    } 
 
    @Benchmark 
    public void barrage(Blackhole bh1) throws InterruptedException { 
        BarrageDTO barrage = new BarrageDTO(); 
        barrage.setActivityId(5368); 
        ApiResult activityBarrages = barrageService.getActivityBarrages(barrage); 
        bh1.consume(activityBarrages); // 防止jit陷阱 
    } 
 
    public static void main(String[] args) throws RunnerException { 
        Options build = new OptionsBuilder().include(JMHFirstBenchmark.class.getSimpleName()) 
                .build(); 
        new Runner(build).run(); 
    } 
}

问题:jmh执行完, 应用还在启动中,会报错,但不影响jmh的使用。

本文参考链接:https://www.cnblogs.com/maohuidong/p/15566091.html