这段时间一直在走流程测试,今天大哥过来,让他看了下我的代码还有点问题,回头还要修改下以前购买商品的帖子,今天先说下接口的并发测试吧,以前都是用Jmeter来做并发测试,今天本来也打算用来着,大哥说那个太麻烦了直接用JUnit提供的ContiPerf,就有了今天的帖子嘿嘿!
需要先导入一个pom文件
org.databene contiperf2.3.4
然后直接在springboot的Test类里 contextLoads 方法上添加 @PerfTest 注解,想这样
@Test
@PerfTest(threads = 50, duration = 30000)
void contextLoads() {
}
@PerfTest后面的参数是50个线程,30秒执行完,更多参数如下
@documented
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface PerfTest {
int invocations() default 1;
int duration() default -1;
int threads() default 1;
int rampUp() default 0;
int warmUp() default 0;
boolean cancelonViolation() default false;
Class extends WaitTimer> timer() default None.class;
double[] timerParams() default {};
Class extends Clock>[] clocks() default {};
}
完整代码
private static String url = "http://localhost:8080/order/";
@Rule
public ContiPerfRule i = new ContiPerfRule();
static int succss = 0;
static int fail = 0;
@Test
@PerfTest(threads = 50, duration = 30000)
void contextLoads() {
try {
Snowflake sf = new Snowflake(2, 5, true);
String userId = sf.nextIdStr().substring(11, 19);
String planNo = "954410189564411904";
JSonObject msg = new JSonObject();
msg.put("userId", userId);
msg.put("planNo", planNo);
sendParam(msg, "接口地址");
succss++;
System.out.println("================================");
} catch (Exception e) {
fail++;
} finally {
System.err.println(Thread.currentThread().getId() + "===success=" + succss + " fail=" + fail);
}
}
protected void sendParam(JSonObject msg, String addr) {
String request = JSON.toJSonString(msg);
log.info("request=={}", request);
String response = HttpUtil.post(url + addr, request);
log.info("response=={}", response);
}
HttpUtil.post(),用的是hutool的,可以自己去导入。
这里需要注意下,我用的spring-boot-starter-test是2.3.6.RELEASE 版本的,版本太高了可以能不能使用@Rule注解。



