最近项目上备战双十一直播,届时上万用户登录系统进行购买,为了尽可能支持多的用户进行购买,所以进行了大量性能测试。
但系统设计了限流排队,超过阈值就会在队列外进行排队,为了模拟真实用户行为,就会涉及到API重试,找了很多方式,在jmeter官方接口文档上面找到这样一个方式。
网上也有推荐while controller的,其实这种方式有些合适
我这里使用了BeanShell Assertion,编写一些java脚本,也可以使用其它BeanShell,只是执行顺序不太一样。
import org.apache.jmeter.samplers.SampleResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
String resCode = new String(ResponseCode);
int queueMaxCalls = 360;
String sampleLabel = SampleResult.getSampleLabel();
String sampleLabelRetry = SampleResult.getSampleLabel() + "-retry";
while (resCode.equals("429") && queueMaxCalls > 0) {
SampleResult.setSampleLabel(sampleLabelRetry);
Thread.sleep(1000);
SampleResult result = ctx.getCurrentSampler().sample(null);
resCode = new String(result.ResponseCode);
maxCalls--;
log.info("step result: " + resCode + ", queueMaxCalls:" + maxCalls);
SampleResult.addSubResult(result);
SampleResult.setResponseCode(result.getResponseCode());
SampleResult.setResponseData(result.getResponseData());
JSONObject responseObj = JSON.parseObject(result.getResponseDataAsString());
if (result.getResponseCode().equals("200")) {
String orderNo = responseObj.get("orderNo").toString();
vars.put("orderNo",orderNo);
}
SampleResult.setResponseHeaders(result.getResponseHeaders());
SampleResult.setResponseMessage(result.getResponseMessage());
SampleResult.setSampleCount(SampleResult.getSampleCount() + result.getSampleCount());
SampleResult.setSampleLabel(sampleLabel);
SampleResult.setSampleCount(result.getSampleCount());
SampleResult.setContentType(result.getContentType());
SampleResult.setDataEncoding("UTF-8");
SampleResult.setSuccessful(result.isSuccessful());
if(result.isSuccessful()) SampleResult.setResponseOK();
}
①ctx.getCurrentSampler().sample(null); 的作用是重新发起当前sampler请求。
②JSONObject responseObj = JSON.parseObject(result.getResponseDataAsString());
if (result.getResponseCode().equals(“200”)) {
String orderNo = responseObj.get(“orderNo”).toString();
vars.put(“orderNo”,orderNo);
}
这一段转成json是因为通过这种方式重新发起请求后,请求下面直接用json抽取字段的值就会为空,所以要在BeanShell中一起重新赋值。
不过导入json包时,要先下载fastjson-1.2.68.jar放在apache-jmeter-5.2.1\lib目录下,本人提供下载这一个版本,有需要自取。
链接: https://pan.baidu.com/s/1hyvR-yavCMZpg6X4McaMuA 提取码: b279 复制这段内容后打开百度网盘手机App,操作更方便哦