一般使用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