jmeter ctx.getCurrentSampler().sample(null)进行sampler请求重试

最近项目上备战双十一直播,届时上万用户登录系统进行购买,为了尽可能支持多的用户进行购买,所以进行了大量性能测试。

但系统设计了限流排队,超过阈值就会在队列外进行排队,为了模拟真实用户行为,就会涉及到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,操作更方便哦

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值