JMeter:如何定制Http请求取样器

一般使用JMeter发送HTTP请求时都会用到HTTP Request取样器,这种取样器大多数时候能够满足压力测试的需要。

图1

但也有一些场景,可能需要更加强大的取样器,或者需要定制一些功能,这时就需要自己手动编写取样器。幸好JMeter为我们提供了这样的扩展点,也就是下面将要介绍的java Requset取样器。

图2

通过java Requset取样器扩展功能,需要用到如下接口或抽象类:

接口:

org.apache.jmeter.protocol.java.sampler.JavaSamplerClient

抽象类:

org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient

需要引入JMeter的如下的包。当然,如果用到其它第三方组件,它们的包也是要引入的

XML 复制代码
		<dependency>
			<groupId>org.apache.jmeter</groupId>
			<artifactId>ApacheJMeter_core</artifactId>
			<version>5.6.3</version>
		</dependency>
		<dependency>
			<groupId>org.apache.jmeter</groupId>
			<artifactId>ApacheJMeter_java</artifactId>
			<version>5.6.3</version>
		</dependency>

下面提供一个简单的例子:

java 复制代码
package com.jmeter.client;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Iterator;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpPerfTester extends AbstractJavaSamplerClient {

  private static final Logger log = LoggerFactory.getLogger(HttpPerfTester.class);

  private CloseableHttpClient httpClient;

  @Override
  public void setupTest(JavaSamplerContext context) {
    super.setupTest(context);

    httpClient = HttpClients.createDefault();
  }

  @Override
  public SampleResult runTest(JavaSamplerContext ctx) {
    String url = ctx.getParameter("cfg.url");
    String reqtBodyFilePath = ctx.getParameter("cfg.reqtBodyFile");
    Iterator<String> paramNameItr = ctx.getParameterNamesIterator();

    HttpPost httpPost = new HttpPost(url);

    SampleResult sampleResult = new SampleResult();
    sampleResult.setSampleLabel("httpClientPerfTest");
    sampleResult.sampleStart();

    try {
      byte[] reqtBodyBuf = Files.readAllBytes(Paths.get(reqtBodyFilePath));

      ByteArrayEntity reqtEntity = new ByteArrayEntity(reqtBodyBuf, ContentType.APPLICATION_JSON);
      httpPost.setEntity(reqtEntity);
      httpPost.addHeader("Content-Type", "application/json");

      while (paramNameItr.hasNext()) {
        String headerName = paramNameItr.next();
        String headerValue = ctx.getParameter(headerName);

        if (headerName.startsWith("httpHeader.")) {
          headerName = headerName.substring(headerName.indexOf("." + 1));

          log.info(headerName + ":" + headerValue);
          httpPost.addHeader(headerName, headerValue);
        }
      }

      CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

      if (httpResponse != null) {
        int statusCode = httpResponse.getStatusLine().getStatusCode();

        HttpEntity respEntity = httpResponse.getEntity();

        byte[] respBodyBuf = EntityUtils.toByteArray(respEntity);

        EntityUtils.consume(reqtEntity);
        EntityUtils.consume(respEntity);

        String reqtHeaderStr = "";
        for (Header header : httpPost.getAllHeaders()) {
          reqtHeaderStr += header.getName() + ":" + header.getValue() + "\n";
        }
        sampleResult.setRequestHeaders(reqtHeaderStr);
        sampleResult.setSamplerData(new String(reqtBodyBuf, "UTF-8"));

        sampleResult.setDataType(SampleResult.TEXT);
        sampleResult.setResponseData(new String(respBodyBuf, "UTF-8"), "UTF-8");
        sampleResult.setResponseCode("" + statusCode);
        sampleResult.setResponseMessage("" + statusCode);

        String respHeaderStr = "";
        for (Header header : httpResponse.getAllHeaders()) {
          respHeaderStr += header.getName() + ":" + header.getValue() + "\n";
        }
        sampleResult.setResponseHeaders(respHeaderStr);

        sampleResult.setSuccessful(true);

      } else {
        sampleResult.setSuccessful(false);
      }
    } catch (Exception e) {
      log.error("runTest error", e);

      sampleResult.setSuccessful(false);
      sampleResult.setResponseMessage(e.toString());
    } finally {
      sampleResult.sampleEnd();
    }

    return sampleResult;
  }

  @Override
  public Arguments getDefaultParameters() {
    Arguments args = new Arguments();
    args.addArgument("cfg.url", "http://15.66.247.19:15050/PASS/8761");
    args.addArgument("cfg.reqtBodyFile", "D:/Temp/8761_reqt.txt");
    args.addArgument("httpHeader.src-service", "APTranditionalService");

    return args;
  }

  @Override
  public void teardownTest(JavaSamplerContext context) {
    super.teardownTest(context);

    if (httpClient != null) {
      try {
        httpClient.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}

编译后打包,比如打的包名:perf.jar,然后将它放到${jmeter_home}/lib/ext目录下,重启JMeter后,就能在java Request中看到图2中的结果。

当执行压力测试后,就可以在View Result Tree中看到测试结果:

图3

相关推荐
钱多多_qdd3 分钟前
spring cache源码解析(四)——从@EnableCaching开始来阅读源码
java·spring boot·spring
waicsdn_haha5 分钟前
Java/JDK下载、安装及环境配置超详细教程【Windows10、macOS和Linux图文详解】
java·运维·服务器·开发语言·windows·后端·jdk
Q_192849990616 分钟前
基于Spring Boot的摄影器材租赁回收系统
java·spring boot·后端
Code_流苏18 分钟前
VSCode搭建Java开发环境 2024保姆级安装教程(Java环境搭建+VSCode安装+运行测试+背景图设置)
java·ide·vscode·搭建·java开发环境
禁默1 小时前
深入浅出:AWT的基本组件及其应用
java·开发语言·界面编程
Cachel wood1 小时前
python round四舍五入和decimal库精确四舍五入
java·linux·前端·数据库·vue.js·python·前端框架
Code哈哈笑1 小时前
【Java 学习】深度剖析Java多态:从向上转型到向下转型,解锁动态绑定的奥秘,让代码更优雅灵活
java·开发语言·学习
gb42152871 小时前
springboot中Jackson库和jsonpath库的区别和联系。
java·spring boot·后端
程序猿进阶1 小时前
深入解析 Spring WebFlux:原理与应用
java·开发语言·后端·spring·面试·架构·springboot