首页 > 解决方案 > 我可以在 jmeter 的线程组中的所有线程中使用变量吗?

问题描述

我正在尝试为限速行为创建一个测试计划。我设置了一个规则,在每分钟 X 个请求后阻塞,我想检查我是否得到响应代码 200,直到我达到 X 个请求,然后得到 429。我创建了一个在所有线程之间共享的计数器,但是这似乎是一团糟,因为它不是线程安全的。

这是我的 beanshell“一次唯一的控制器”:

String props_pre_fix = ${section_id} + "-" + ${START.HMS};
props.remove("props_pre_fix" + ${section_id}, props_pre_fix);
props.put("props_pre_fix" + ${section_id}, props_pre_fix);

props.put(props_pre_fix + "_last_response_code", "200");
props.put(props_pre_fix + "_my_counter", "0");

这是 beanshell 断言:

String props_pre_fix = props.get("props_pre_fix" + ${section_id});
//log.info("props_pre_fix " + props_pre_fix);

//extract my counter from props
int my_counter = Integer.parseInt(props.get(props_pre_fix + "_my_counter"));

//extract last response code
String last_response_code = props.get(props_pre_fix + "_last_response_code");
log.info("last_response_code " + last_response_code);

//if last seconds is greater than current seconds it means we are in a new minute - set counter to zero
if(last_response_code.equals("429") && ResponseCode.equals("200")){
    log.info("we moved to a new minute - my_counter should be zero");
    my_counter = 0;
}

//increase counter
my_counter++;
log.info("set counter with value: " + my_counter);
//save counter
props.put(props_pre_fix + "_my_counter", my_counter + "");
log.info("counter has set with value: " + my_counter);

if (ResponseCode.equals("200")) {
    props.put(props_pre_fix + "_last_response_code", "200");
    if(my_counter <= ${current_limit}){
        Failure = false;
    } 
    else {
        Failure = true;
        FailureMessage = "leakage of " + (my_counter - ${current_limit}) + " requests";
    }
} 
else if (ResponseCode.equals("429")) {
    props.put(props_pre_fix + "_last_response_code", "429");
     if(my_counter > ${current_limit}){
            Failure = false;
    } 
}

我正在使用道具分享柜台,但我显然觉得这不是正确的做法。你能建议我怎么做吗?

标签: jmeterrate-limitingtest-plan

解决方案


我认为不可能使用 JMeter 断言自动测试此要求,因为您无法访问当前的吞吐量,所以我宁愿建议考虑交叉检查每秒响应代码和每秒事务图表(可以安装使用JMeter 插件管理器

所有的200429响应都可以使用如下配置的响应断言标记为成功:

在此处输入图像描述

如果出于某种原因您仍想以编程方式执行此操作,您可能需要查看用于在 STDOUT 中显示当前吞吐量的Summariser类源。

另请注意,从 JMeter 3.1 开始,您应该使用 JSR223 测试元素和 Groovy 语言编写脚本。


推荐阅读