首先, 需要引入jmh的包:
<!-- https://mvnrepository.com/artifact/org.openjdk.jmh/jmh-core -->
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.21</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjdk.jmh/jmh-generator-annprocess -->
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.21</version>
<scope>test</scope>
</dependency>
創建測試類
package cn.ygl.demo.jmh;
import cn.ygl.demo.DemoApplication;
import cn.ygl.demo.service.JSONService;
import cn.ygl.demo.service.impl.FastJsonService;
import cn.ygl.demo.service.impl.GsonService;
import com.alibaba.fastjson.JSONObject;
import org.junit.Test;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;
import java.util.UUID;
@State(value = Scope.Thread)
public class JMHTests {
private String reqStr;
private ConfigurableApplicationContext context;
private JSONService fastjsonService;
private JSONService gsonService;
@Test
public void test() throws RunnerException {
Options options = new OptionsBuilder().include(JMHTests.class.getSimpleName())
.warmupIterations(2).measurementIterations(2).forks(1).build();
new Runner(options).run();
}
@Setup
public void init() {
JSONObject object = new JSONObject();
object.put("requestId", UUID.randomUUID().toString());
object.put("requestName", "test");
object.put("requestData", "122345");
object.put("requestType", "POST");
reqStr = object.toString();
System.err.println("init....");
context = SpringApplication.run(DemoApplication.class);
fastjsonService = context.getBean(FastJsonService.class);
gsonService = context.getBean(GsonService.class);
}
@TearDown
public void finish(){
context.close();
}
@Benchmark
public void testGson(){
gsonService.getRequestId(reqStr);
}
@Benchmark
public void testFastJSON(){
fastjsonService.getRequestId(reqStr);
}
}
@Setup默認是初始化一次的
注意, finish方法要記得關閉context, 否則會報錯誤JMH had finished, but forked VM did not exit, are there stray running threads? Waiting 24 seconds more... , 這是因爲內嵌的tomcat線程沒結束導致的(網上有些教程並沒有添加這個@TearDown方法, 我不知道爲什麼他們不報錯, 我的會報錯, 不知道還有沒有其他人也這樣)
這樣跑基準測試的時候就不會報錯了, 結果如下:
下面貼上引入的倆個bean代碼
@Service
@Qualifier("fastjson")
public class FastJsonService implements JSONService {
@Override
public String getRequestId(String str) {
return ((JSONObject)JSONObject.parse(str)).getString("requestId");
}
}
@Service
@Qualifier("gson")
public class GsonService implements JSONService {
@Override
public String getRequestId(String str) {
return new Gson().fromJson(str, ReqData.class).getRequestId();
}
}