创建JAVA请求
选中创建的线程组,点击右键,添加Sampler→Java Request → 切换到自定义的测试类
中间可能自定义的jar包没有在列表中展示,确保进行了如下操作:
1, 确定按要求实现了jmeter, 如: 继承JavaSamplerClient
2, 确定以 Runnable JAR file导出jar, 并且"Launch configuration"选择正确
3, 确定放到 jmeter的 /lib/ext下
4, 确定重启了 jmeter
创建java工程:添加jmeter相关的pom依赖
jmeter相关的pom依赖
<groupId>org.apache.jmeter
<artifactId>jorphan
<version>3.1
<artifactId>slf4j-api
<groupId>org.slf4j
<artifactId>gson
<groupId>com.google.code.gson
</dependency>
创建类实现JavaSamplerClient接口或者继承AbstractJavaSamplerClient,重写如下方法:
public Arguments getDefaultParameters() // 设置可用参数及默认值
public void setupTest() //每个线程执行测试前执行一次,执行初始化工作
public SampleResult runTest(JavaSamplerContext arg0) // 开始测试从arg0参数获取参数值
public void teardownTest(JavaSamplerContext arg0) //测试结束时调用
如下java代码是针对dubbo通信协议的:
public void setupTest(){
//定义测试初始值,setupTest只在测试开始前使用
System.out.println("setupTest");
}
@Override
public SampleResult runTest(JavaSamplerContext arg0) {
SampleResult sr =new SampleResult(); ;
try {
//获取参数
ID = arg0.getParameter("ID");
URL = arg0.getParameter("URL");
VERSION = arg0.getParameter("VERSION");
SERVICE_NAME = arg0.getParameter("SERVICE_NAME");
//dubbo初始化
init();
//jmeter结果对象
sr.setSampleLabel(label);
sr.sampleStart();
EmailGenerator demoService = (EmailGenerator)object;
String hello = demoService.generate();
sr.setResponseCode("00000");
sr.setResponseMessage(hello);
sr.setSuccessful(true);
sr.sampleEnd();// jmeter 结束统计响应时间标记
}catch (Exception e) {
e.printStackTrace();
sr.setResponseCode("999");
sr.setResponseMessage(e.getMessage());
sr.setSuccessful(false);
}
return sr;
}
public Arguments getDefaultParameters(){
//参数定义,显示在前台,也可以不定义
Arguments params =new Arguments();
params.addArgument("ID","");
params.addArgument("URL","");
params.addArgument("VERSION","");
params.addArgument("SERVICE_NAME","");
return params;
}
public void teardownTest(JavaSamplerContext arg0){
super.teardownTest(arg0);
}
// 测试执行的main函数
public static void main(String[] args) {
// TODO Auto-generated method stub
Arguments params =new Arguments();
params.addArgument("ID","");
params.addArgument("URL","");
params.addArgument("VERSION","");
params.addArgument("SERVICE_NAME","");
JavaSamplerContext arg0 =new JavaSamplerContext(params);
TestConsumer test =new TestConsumer();
test.setupTest(arg0);
test.runTest(arg0);
test.teardownTest(arg0);
}
导出为可执行jar包(直接运行mvn clean install,找到target目录下的jar包),放入Jmeter根目录/lib/ext目录下
以管理员身份打开Jmeter创建线程组、添加Java 请求Sampler,添加结果树、添加聚合报告;
网友评论