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

相关推荐
Lizhihao_1 分钟前
JAVA-队列
java·开发语言
喵叔哟11 分钟前
重构代码之移动字段
java·数据库·重构
喵叔哟11 分钟前
重构代码之取消临时字段
java·前端·重构
fa_lsyk13 分钟前
maven环境搭建
java·maven
Daniel 大东32 分钟前
idea 解决缓存损坏问题
java·缓存·intellij-idea
wind瑞39 分钟前
IntelliJ IDEA插件开发-代码补全插件入门开发
java·ide·intellij-idea
HappyAcmen39 分钟前
IDEA部署AI代写插件
java·人工智能·intellij-idea
马剑威(威哥爱编程)44 分钟前
读写锁分离设计模式详解
java·设计模式·java-ee
鸽鸽程序猿1 小时前
【算法】【优选算法】前缀和(上)
java·算法·前缀和
修道-03231 小时前
【JAVA】二、设计模式之策略模式
java·设计模式·策略模式