首页 > 解决方案 > 需要在 JMETER 测试中加载静态内容

问题描述

我需要想办法在 Jmeter 的预处理步骤中从包含 id 列表的文件中加载内容。这需要只发生一次,而不是每次请求都发生。所以它应该像 -

  1. 一次从文件中加载所有静态 ID 列表。
  2. 对于每个请求,从该列表中随机选择一个 id。
  3. 发布请求

我正在尝试探索 JSR223 预处理器,但到目前为止运气不佳。此外,我不确定预处理器是否针对我不想要的每个请求执行。

我当前的 JSR 预处理器如下所示 -

import java.util.*;
import java.io.*;

try {

    Random generator = new Random();
        List<String> uuids = new ArrayList<String>();
    int n = 1000;

    try(BufferedReader br = new BufferedReader(new FileReader("/uuids.txt"))) {
        String line = br.readLine();

        while (line != null) {
            uuids.add(line);
            line = br.readLine();
        }
    }

    int rn = uuids.get(generator.nextInt(n));
    vars.put("some_file", "/files/" + uuids.get(rn) + ".json.gz");
} catch (Throwable ex) {
    log.error("Something went wrong", ex);
    throw ex;
}```

标签: javajmeter

解决方案


您的方法有点错误,因为:

  1. JSR223 PreProcessor 在其范围内的每个请求之前执行
  2. JSR223 PreProcessor 由每个线程执行(虚拟用户)

所以我会推荐以下增强:

  1. 将设置线程组添加到您的测试计划
  2. 使用以下代码将JSR223 Sampler添加到其中:

    SampleResult.setIgnore()
    props.put('uuids', new File('uuids.txt').readLines())
    

    这将使您仅通过一个线程读取文件一次。

  3. 每当您想访问随机 uuid 时,都可以使用以下__groovy()函数:

    ${__groovy(props.get('uuids').get(org.apache.commons.lang3.RandomUtils.nextInt(0\,props.get('uuids').size())),)} 
    

有关 JMeter 中 Groovy 脚本的更多信息:Apache Groovy - 为什么以及如何使用它


推荐阅读