JMeter自定义采样器插件开发

1. 简介

JMeter支持插件机制,只需要将打包好的jar包放到lib/ext/下面,JMeter就会动态的加载符合要求的插件。

  • 要扩展UI的话,扩展的Java类的包名必须是.gui.
  • 同样的扩展函数的Java类的包名必须是.function.

2. 需求简介

本文演示的是如何自定义一个https 的采样器。

ssl的配置以参数的形式传给JMeter。

3.成品展示

成功展示

失败展示

4. 准备开发环境

新建Maven项目。

4.1 准备pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>httpsSampler</artifactId>
<version>1.0-SNAPSHOT</version> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jmeter-version>3.0</jmeter-version>
</properties> <dependencies>
<dependency>
<groupId>org.apache.jmeter</groupId>
<artifactId>ApacheJMeter_core</artifactId>
<version>${jmeter-version}</version>
<scope>provided</scope>
</dependency> <dependency>
<groupId>org.apache.jmeter</groupId>
<artifactId>ApacheJMeter_java</artifactId>
<version>${jmeter-version}</version>
<scope>provided</scope>
</dependency>
</dependencies> <build>
<finalName>${project.artifactId}</finalName>
<defaultGoal>install</defaultGoal>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>assemble-all</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

4.2 新建Java的GUI类

新建 org.apache.jmeter.protocol.https.control.gui 类,并继承org.apache.jmeter.samplers.gui.AbstractSamplerGui

需要重写几个函数。

/**gui显示的sample的名称**/
public String getStaticLabel()
public String getLabelResource()
//这个方法用于把界面的数据移到Sampler中。
public void modifyTestElement(TestElement testElement)
//界面与Sampler之间的数据交换
public void configure(TestElement el)
//该方法会在reset新界面的时候调用,这里可以填入界面控件中需要显示的一些缺省的值(就是默认显示值)
public void clearGui()
//该方法创建一个新的Sampler,然后将界面中的数据设置到这个新的Sampler实例中。
public TestElement createTestElement()

全代码

package org.apache.jmeter.protocol.https.control.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout; import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel; import org.apache.jmeter.gui.util.JSyntaxTextArea;
import org.apache.jmeter.gui.util.JTextScrollPane;
import org.apache.jmeter.gui.util.VerticalPanel;
import org.apache.jmeter.protocol.https.sampler.HttpsSampler;
import org.apache.jmeter.samplers.gui.AbstractSamplerGui;
import org.apache.jmeter.testelement.TestElement; import org.apache.jorphan.gui.JLabeledTextField;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger; //这个注解必须要有
@SuppressWarnings("deprecation")
public class HttpsSamplerUI extends AbstractSamplerGui { private static final long serialVersionUID = 1L;
private static Logger log = LoggingManager.getLoggerForClass(); private final JLabeledTextField sslVersionField = new JLabeledTextField("SSL版本");
private final JLabeledTextField cipherField = new JLabeledTextField("密码套件");
private final JLabeledTextField twoWayField = new JLabeledTextField("双向");
private final JLabeledTextField caCertField = new JLabeledTextField("CA证书");
private final JLabeledTextField clientCertField = new JLabeledTextField("客户端证书");
private final JLabeledTextField clientP12Field = new JLabeledTextField("客户端私钥"); private final JLabeledTextField requestsStringField = new JLabeledTextField("请求信息"); private final JSyntaxTextArea textMessage = new JSyntaxTextArea(10, 50);
// private final JLabel textArea = new JLabel(JMeterUtils.getResString("kafka.message", "Message"));
private final JLabel textArea = new JLabel("Message");
private final JTextScrollPane textPanel = new JTextScrollPane(textMessage);
public HttpsSamplerUI(){
super();
this.init(); } private void init(){
log.info("Initializing the UI.");
setLayout(new BorderLayout());
setBorder(makeBorder()); add(makeTitlePanel(), BorderLayout.NORTH);
JPanel mainPanel = new VerticalPanel();
add(mainPanel, BorderLayout.CENTER); JPanel DPanel = new JPanel();
DPanel.setLayout(new GridLayout(4, 2));
DPanel.add(sslVersionField);
DPanel.add(cipherField);
DPanel.add(twoWayField);
DPanel.add(caCertField);
DPanel.add(clientCertField);
DPanel.add(clientP12Field);
DPanel.add(requestsStringField); JPanel ControlPanel = new VerticalPanel();
ControlPanel.add(DPanel);
ControlPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.gray), "参数"));
mainPanel.add(ControlPanel); /**这是是输出**/
JPanel ContentPanel = new VerticalPanel();
JPanel messageContentPanel = new JPanel(new BorderLayout());
messageContentPanel.add(this.textArea, BorderLayout.NORTH);
messageContentPanel.add(this.textPanel, BorderLayout.CENTER);
ContentPanel.add(messageContentPanel);
ContentPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.gray), "Content"));
mainPanel.add(ContentPanel); } /**
* 该方法创建一个新的Sampler,然后将界面中的数据设置到这个新的Sampler实例中。
* **/
@Override
public TestElement createTestElement() {
HttpsSampler sampler = new HttpsSampler();
this.setupSamplerProperties(sampler);
return sampler;
} /**
* 该方法会在reset新界面的时候调用,这里可以填入界面控件中需要显示的一些缺省的值。
* **/
@Override
public void clearGui(){
super.clearGui();
this.sslVersionField.setText("TLSv1.2");
this.cipherField.setText("ECDHE-AES256-SHA384");
this.twoWayField.setText("y");
this.caCertField.setText("xxx/xxx/ca.cert");
this.clientCertField.setText("xxx/xxx/client.cert");
this.clientP12Field.setText("xxx/xxx/client.key");
this.requestsStringField.setText("GET /1k.html HTTP1.0\r\n"); } /**
* 界面与Sampler之间的数据交换
* 该方法用于把Sampler中的数据加载到界面中。
* 在实现自己的逻辑之前,先调用一下父类的方法super.configure(el),这样可以确保框架自动为你加载一些缺省数据,比如Sampler的名字。
* **/
@Override
public void configure(TestElement el){
super.configure(el);
HttpsSampler sampler = (HttpsSampler) el;
this.sslVersionField.setText(sampler.getHttpsSslVersion());
this.cipherField.setText(sampler.getHttpsCipher());
this.twoWayField.setText(sampler.getHttpsTwoWay());
this.caCertField.setText(sampler.getHttpsCa());
this.clientCertField.setText(sampler.getHttpsClientCert());
this.clientP12Field.setText(sampler.getHttpsClientP12());
this.requestsStringField.setText(sampler.getHttpsRequest());
} private void setupSamplerProperties(HttpsSampler sampler) {
this.configureTestElement(sampler);
sampler.setSslVersion(this.sslVersionField.getText());
sampler.setCipher(this.cipherField.getText());
sampler.setHttpsTwoWay(this.twoWayField.getText());
sampler.setHttpsCa(this.caCertField.getText());
sampler.setHttpsClientCert(this.clientCertField.getText());
sampler.setHttpsClientP12(this.clientP12Field.getText());
sampler.setHttpsRequest(this.requestsStringField.getText());
} /**gui显示sample的名称**/
@Override
public String getStaticLabel() {
return "Https Sampler";
} @Override
public String getLabelResource() {
throw new IllegalStateException("This shouldn't be called");
} /**
* 这个方法用于把界面的数据移到Sampler中,刚好与上面的方法相反。
* 在调用自己的实现方法之前,请先调用一下super.configureTestElement(e),这个会帮助移到一些缺省的数据。
* **/
@Override
public void modifyTestElement(TestElement testElement) {
HttpsSampler sampler = (HttpsSampler) testElement;
this.setupSamplerProperties(sampler);
} }

4.3 准备Java的采样器

新建org.apache.jmeter.protocol.https.sampler 继承 org.apache.jmeter.samplers.AbstractSampler 实现 org.apache.jmeter.testelement.TestStateListener接口

重写函数

//该方法是JMeter实现对目标系统发起请求实际工作的地方
public SampleResult sample(Entry entry)

这个4个方法必须覆写,否则无法识别

@Override
public void testStarted() { } @Override
public void testStarted(String s) { } @Override
public void testEnded() {
this.testEnded("local");
} @Override
public void testEnded(String s) { }

全代码

package org.apache.jmeter.protocol.https.sampler;

import org.apache.jmeter.samplers.AbstractSampler;
import org.apache.jmeter.samplers.Entry;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.testelement.TestStateListener; import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger; public class HttpsSampler extends AbstractSampler implements TestStateListener { private static final long serialVersionUID = 1L;
private static final String HTTPS_SSL_VERSION = "https.sslVersion";
private static final String HTTPS_CIPHER = "https.cipher";
private static final String HTTPS_TWO_WAY= "https.twoWay";
private static final String HTTPS_CA = "https.caCert";
private static final String HTTPS_CLIENT_CERT = "https.clientCert";
private static final String HTTPS_CLIENT_P12 = "https.clientP12";
private static final String HTTPS_REQUEST = "https.requestsString";
private static final Logger log = LoggingManager.getLoggerForClass(); // 构造函数要为pubilc
public HttpsSampler(){
setName("Https Sampler");
} /**
* 该方法是JMeter实现对目标系统发起请求实际工作的地方
* **/
@Override
public SampleResult sample(Entry entry) {
SampleResult result = new SampleResult();
result.setSampleLabel(getName());
result.sampleStart();
try {
/**
* 采样器执行code处
* **/
result.setRequestHeaders("请求头---请求头展示数据");
result.setSamplerData("设置采样器数据");
if (!getHttpsSslVersion().startsWith("TLS")) {
// stop stopwatch
result.sampleEnd();
result.setSuccessful(false);
// 设置取样器结果里面响应信息
result.setResponseMessage("ssl不为TLS开头,采样失败(示例)");
result.setDataType(org.apache.jmeter.samplers.SampleResult.TEXT);
result.setResponseCode("FAILED");
// 设置响应数据的响应body
result.setResponseData("响应信息---响应体展示数据", null);
// 设置响应数据的响应header
result.setResponseHeaders("响应头信息---响应头展示数据");
}else {
result.sampleEnd();
result.setSuccessful(true);
result.setResponseCodeOK();
} } catch (Exception e) {
result.sampleEnd(); // stop stopwatch
result.setSuccessful(false);
result.setResponseMessage("Exception: " + e);
// get stack trace as a String to return as document data
java.io.StringWriter stringWriter = new java.io.StringWriter();
e.printStackTrace(new java.io.PrintWriter(stringWriter));
result.setResponseData(stringWriter.toString(), null);
result.setDataType(org.apache.jmeter.samplers.SampleResult.TEXT);
result.setResponseCode("FAILED");
}
return result;
} public void setSslVersion(String sslVersion){
setProperty(HTTPS_SSL_VERSION, sslVersion);
} public void setCipher(String cipher){
setProperty(HTTPS_CIPHER, cipher);
} public void setHttpsTwoWay(String twoWay){
setProperty(HTTPS_TWO_WAY, twoWay);
} public void setHttpsCa(String ca){
setProperty(HTTPS_CA, ca);
} public void setHttpsClientCert(String clientCert){
setProperty(HTTPS_CLIENT_CERT, clientCert);
} public void setHttpsClientP12(String clientP12){
setProperty(HTTPS_CLIENT_P12, clientP12);
} public void setHttpsRequest(String requestsString){
setProperty(HTTPS_REQUEST, requestsString);
} public String getHttpsSslVersion(){
return getPropertyAsString(HTTPS_SSL_VERSION);
} public String getHttpsCipher(){
return getPropertyAsString(HTTPS_CIPHER);
} public String getHttpsTwoWay(){
return getPropertyAsString(HTTPS_TWO_WAY);
} public String getHttpsCa(){
return getPropertyAsString(HTTPS_CA);
} public String getHttpsClientCert(){
return getPropertyAsString(HTTPS_CLIENT_CERT);
} public String getHttpsClientP12(){
return getPropertyAsString(HTTPS_CLIENT_P12);
} public String getHttpsRequest(){
return getPropertyAsString(HTTPS_REQUEST);
} @Override
public void testStarted() { } @Override
public void testStarted(String s) { } @Override
public void testEnded() {
this.testEnded("local");
} @Override
public void testEnded(String s) { }
}

5. 打包&部署

maven install后会在target/下会有打包好的jar包。

然后将jar包拷贝到lib/ext/下,启动JMeter。选取新增的取样器即可。

6. 参考文章

JMeter扩展插件实现对自定义协议进行支持

JMeter自定义采样器插件开发的更多相关文章

  1. elasticsearch 自定义similarity 插件开发

    转自:http://www.chepoo.com/elasticsearch-similarity-custom-plug-in-development.html 在搜索开发中,我们要修改打分机制,就 ...

  2. JMeter自定义HTTP组件

    JMeter是一个优秀的开源项目,我们可以在jmeter的官网了解到如何使用和如何二次开发:https://jmeter.apache.org/ 因工作需要,最近做了一个JMeter自定义的http组 ...

  3. Jmeter自定义编写Java代码调用socket通信

    一.前言 最近需要测试一款手机游戏的性能,找不到啥录制脚本的工具,然后,另外想办法.性能测试实际上就是对服务器的承载能力的测试,和各种类型的手机客户端没有啥多大关系,手机再好,服务器负载不了,也不能够 ...

  4. jmeter自定义并发用户数图形插件介绍

    Stepping Thread Group马上要被废弃了,废弃原因不知道,官方推荐使用 BlazeMeter Inc.公司贡献的插件Concurrency Thread Group,配合 Throug ...

  5. Jmeter自定义Java请求开发

    一.本次实验目的 IDEA新建maven项目,使用java开发自定义jmeter的请求. 本次开发使用的代码,会百度云分享给大家. 二.本次实验环境 Idea 2017.02 Jmeter 5.1.1 ...

  6. 9.Jmeter自定义Sample(自定义测试内容)完成测试

    问题:在某些场景下我们会发现Jmeter里面提供的各种Sample不能满足自己的需求,应为这个世界上的压力测试的逻辑本来就是千变万化的,所以这个时候我们如果自己实现一套测试逻辑(当Jmeter的基本e ...

  7. ionic2 自定义cordova插件开发以及使用 (Android)

    如何写一个cordova 用于ionic2项目中呢,在搜索了一番之后,千篇一律,我都怀疑那些文章是不是全部都是复制来复制去的,而且都不是很详细.我自己也捣鼓了一下午,踩了很多坑.所以特此写这下这篇,记 ...

  8. Jmeter自定义Java请求,继承AbstractJavaSamplerClient

    首先,使用Eclipse新建一个项目,然后从Jmeter的lib/ext目录下中拷贝ApacheJMeter_java.jar和ApacheJMeter_core.jar两个文件,然后引入这两个JAR ...

  9. [转]jmeter 自定义测试脚本

    http://blog.csdn.net/kash_chen007/article/details/37690411 http://wangym.iteye.com/blog/731729 1.创建一 ...

随机推荐

  1. C++算法代码——扫雷游戏

    题目来自:http://218.5.5.242:9018/JudgeOnline/problem.php?id=1685 题目描述 扫雷游戏是一款十分经典的单机小游戏. 在 n 行 m 列的雷区中有一 ...

  2. 死磕Spring之IoC篇 - 深入了解Spring IoC(面试题)

    该系列文章是本人在学习 Spring 的过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring 源码分析 GitHub 地址 进行阅读 Spring 版本:5.1. ...

  3. Java中出现Unhandled exception的原因

    说明某个方法在方法声明上已经声明了会抛异常,那么在调用这个方法的时候,就必须做异常处理,处理的方式有2种,要么try-catch这个异常,要么继续往上一层抛出这个异常,这是java语法要求的,必须这么 ...

  4. python行与列显示不全

    在显示数据框时添加以下代码 #显示所有列 pd.set_option('display.max_columns', None) #显示所有行 pd.set_option('display.max_ro ...

  5. 重复代码的克星,高效工具 VSCode snippets 的使用指南

    为什么要用 snippets(代码段)? 不管你使用何种编程语言,在我们日常的编码工作中,都会存在有大量的重复代码编写,例如: 日志打印: console.log,log.info('...') 输出 ...

  6. 机器学习系统或者SysML&DL笔记(一)

    前言 在使用过TVM.TensorRT等优秀的机器学习编译优化系统以及Pytorch.Keras等深度学习框架后,总觉得有必要从理论上对这些系统进行一些分析,虽然说在实践中学习是最快最直接的(指哪儿打 ...

  7. CCF(通信网络):简单DFS+floyd算法

    通信网络 201709-4 一看到题目分析了题意之后,我就想到用floyd算法来求解每一对顶点的最短路.如果一个点和任意一个点都有最短路(不为INF),那么这就是符合的一个答案.可是因为题目超时,只能 ...

  8. .NET MVC & Web API Cors让AJAX 实现跨域

    什么是Cors? CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing).它允许浏览器向跨源服务器,发出XMLHttpReq ...

  9. 动态规划-最长公共上升子序列-n^2解法

    1. 题目描述 给定两个数列\(A, B\),如果他们都包含一段位置不一定连续的数,且数值是严格递增的,那么称这一段数是两个数列的公共上升子序列.求\(A\)和\(B\)的最长公共上升子序列. 输入格 ...

  10. 两种常见Content-type的方便理解

    application/x-www-form-urlencoded:key=value键值对application/json:{name:"张三"} JSON字符串塞到请求的bod ...