1、打开IntelliJ IDEA,新建一个Maven项目

2、导入Jmeter的依赖包
在idea中导入jmeter下的ApacheJMeter_core.jar和ApacheJMeter_functions.jar依赖包


3、添加java自定义函数
要实现扩展JMeter function,主要有两点:
实现function的类的package声明必须包含”.functions”需要继承org.apache.jmeter.functions.AbstractFunction,并且实现相应的方法。
扩展AbstractFunction类

package org.apache.jmeter.functions;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;
import org.apache.jmeter.util.JMeterUtils;
public class MyFunction extends AbstractFunction {
//自定义function的描述
private static final List<String> desc = new LinkedList<>();
//function名称
private static final String KEY = "__MyFunction";
static {
desc.add("systemnum");
desc.add("sizenum");
}
private CompoundVariable systemnum;
private CompoundVariable sizenum;
// 函数的逻辑执行主体
/** {@inheritDoc} */
@Override
public String execute(SampleResult previousResult, Sampler currentSampler)
throws InvalidVariableException {
long num = Long.valueOf(systemnum.execute());
int size = Integer.valueOf(sizenum.execute());
String str = Long.toHexString(num);;
while(str.length()<size){
str = "0" + str;
}
return str;
}
// 用来接收和处理GUI界面的参数的传值
/** {@inheritDoc} */
@Override
public void setParameters(Collection<CompoundVariable> parameters) throws InvalidVariableException {
checkParameterCount(parameters, 2);
Object[] values = parameters.toArray();
systemnum = (CompoundVariable) values[0];
sizenum = (CompoundVariable) values[1];
}
// 用来定义函数的名称,把自定义的内容显示在函数对话框中
/** {@inheritDoc} */
@Override
public String getReferenceKey() {
return KEY;
}
// 用来设置GUI界面的函数对话框,把自己定义的参数给显示在jmeter的GUI界面上
/** {@inheritDoc} */
@Override
public List<String> getArgumentDesc() {
return desc;
}
}
4、将自定义函数编译成.class文件*
由于Maven默认用的是JDK1.5去编译,所以使用JDK1.8版本进行编译的时候报错了。

在pom.xml中添加以下代码,然后进行编译(Build->Build project),编译成功

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>

5、将.class文件添加到ApacheJMeter_functions.jar中
使用WinRAR打开ApacheJMeter_functions.jar,进入\org\apache\jmeter\functions目录下

点击【添加】,选择编译好的.class文件
6、
重新启动jmeter
打开函数助手

自定义函数添加成功

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)