JMETER通过java代码通过代码/ JMETER API实现示例进行负载测试
本教程试图解释Jmeter的基本设计,功能和用法,Jmeter是用于在应用程序上执行负载测试的优秀工具。通过使用jmeter GUI,我们可以
根据我们的要求为请求创建测试样本并执行具有多个用户负载的样本。
由于jmeter工具是使用JAVA完全开发的,我们可以编写java代码来做同样的事情而不使用jmeter的GUI,不建议实现java代码进行负载测试,它只是一个概念证明来编写使用jmeter库通过java代码进行采样。
Jmeter作为非常好的文档/ API,在浏览了jmeter源代码和其他参考资源之后,编写了以下示例代码。
预先决条件:
JMeter的JAVA> = 1.6Eclipse或net beans编辑器
在理解以下代码之前,我们必须具备jmeter如何工作的基本知识。
最初我们需要加载jmeter属性,这些属性将由jmeter类/库在代码的后期使用
JMETERJAVA >= 1.6Eclipse or net beans editor
//JMeter Engine
StandardJMeterEngine jmeter = new StandardJMeterEngine();
//JMeter initialization (properties, log levels, locale, etc)
JMeterUtils.setJMeterHome(jmeterHome.getPath());
JMeterUtils.loadJMeterProperties(jmeterProperties.getPath());
JMeterUtils.initLogging();// you can comment this line out to see extra log messages of i.e. DEBUG level
JMeterUtils.initLocale();
1.创建“测试计划”对象和JOrphan HashTree
//JMeter Test Plan, basically JOrphan HashTree
HashTree testPlanTree = new HashTree();
// Test Plan
TestPlan testPlan = new TestPlan("Create JMeter Script From Java Code");
testPlan.setProperty(TestElement.TEST_CLASS, TestPlan.class.getName());
testPlan.setProperty(TestElement.GUI_CLASS, TestPlanGui.class.getName());
testPlan.setUserDefinedVariables((Arguments) new ArgumentsPanel().createTestElement());
2.采样器:添加“Http Sample”对象
采样器告诉JMeter将请求发送到服务器并等待响应。它们按照它们在树中出现的顺序进行处理。控制器可用于修改采样器的重复次数
// First HTTP Sampler - open uttesh.com
HTTPSamplerProxy examplecomSampler = new HTTPSamplerProxy();
examplecomSampler.setDomain("uttesh.com");
examplecomSampler.setPort(80);
examplecomSampler.setPath("/");
examplecomSampler.setMethod("GET");
examplecomSampler.setName("Open uttesh.com");
examplecomSampler.setProperty(TestElement.TEST_CLASS, HTTPSamplerProxy.class.getName());
examplecomSampler.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName());
3.Loop控制器
循环控制器将执行循环迭代声明的样本数。
// Loop Controller
LoopController loopController = new LoopController();
loopController.setLoops(1);
loopController.setFirst(true);
loopController.setProperty(TestElement.TEST_CLASS, LoopController.class.getName());
loopController.setProperty(TestElement.GUI_CLASS, LoopControlPanel.class.getName());
loopController.initialize();
4.Thread Group
线程组元素是任何测试计划的起点。所有控制器和采样器必须位于线程组下。其他元素,例如Listeners,可以直接放在测试计划下,在这种情况下,它们将应用于所有线程组。顾名思义,线程组元素控制JMeter用于执行测试的线程数。
// Thread Group
ThreadGroup threadGroup = new ThreadGroup();
threadGroup.setName("Sample Thread Group");
threadGroup.setNumThreads(1);
threadGroup.setRampUp(1);
threadGroup.setSamplerController(loopController);
threadGroup.setProperty(TestElement.TEST_CLASS, ThreadGroup.class.getName());
threadGroup.setProperty(TestElement.GUI_CLASS, ThreadGroupGui.class.getName());
5. 将采样器,控制器......等添加到测试计划中
// Construct Test Plan from previously initialized elements
testPlanTree.add(testPlan);
HashTree threadGroupHashTree = testPlanTree.add(testPlan, threadGroup);
threadGroupHashTree.add(examplecomSampler);
// save generated test plan to JMeter's .jmx file format
SaveService.saveTree(testPlanTree, new FileOutputStream("report\\jmeter_api_sample.jmx"));
上面的代码将生成我们从代码中编写的jmeter脚本。
5.添加摘要和报告
//add Summarizer output to get test progress in stdout like:
// summary = 2 in 1.3s = 1.5/s Avg: 631 Min: 290 Max: 973 Err: 0 (0.00%)
Summariser summer = null;
String summariserName = JMeterUtils.getPropDefault("summariser.name", "summary");
if (summariserName.length() > 0) {
summer = new Summariser(summariserName);
}
// Store execution results into a .jtl file, we can save file as csv also
String reportFile = "report\\report.jtl";
String csvFile = "report\\report.csv";
ResultCollector logger = new ResultCollector(summer);
logger.setFilename(reportFile);
ResultCollector csvlogger = new ResultCollector(summer);
csvlogger.setFilename(csvFile);
testPlanTree.add(testPlanTree.getArray()[0], logger);
testPlanTree.add(testPlanTree.getArray()[0], csvlogger);
Finally Execute the test
// Run Test Plan
jmeter.configure(testPlanTree);
jmeter.run(); System.out.println("Test completed. See " + jmeterHome + slash + "report.jtl file for results");
System.out.println("JMeter .jmx script is available at " + jmeterHome + slash + "jmeter_api_sample.jmx");
System.exit(0);
POC的完整源代码可以在GitHub上找到。点击这里
| import java.io.File; | |
| import java.io.FileOutputStream; | |
| import org.apache.jmeter.config.Arguments; | |
| import org.apache.jmeter.config.gui.ArgumentsPanel; | |
| import org.apache.jmeter.control.LoopController; | |
| import org.apache.jmeter.control.gui.LoopControlPanel; | |
| import org.apache.jmeter.control.gui.TestPlanGui; | |
| import org.apache.jmeter.engine.StandardJMeterEngine; | |
| import org.apache.jmeter.protocol.http.control.gui.HttpTestSampleGui; | |
| import org.apache.jmeter.protocol.http.sampler.HTTPSamplerProxy; | |
| import org.apache.jmeter.reporters.ResultCollector; | |
| import org.apache.jmeter.reporters.Summariser; | |
| import org.apache.jmeter.save.SaveService; | |
| import org.apache.jmeter.testelement.TestElement; | |
| import org.apache.jmeter.testelement.TestPlan; | |
| import org.apache.jmeter.threads.ThreadGroup; | |
| import org.apache.jmeter.threads.gui.ThreadGroupGui; | |
| import org.apache.jmeter.util.JMeterUtils; | |
| import org.apache.jorphan.collections.HashTree; | |
| /** | |
| * | |
| * @author Uttesh Kumar T.H. | |
| */ | |
| public class JMeterAPISampleTest { | |
| public static void main(String[] argv) throws Exception { | |
| //Set jmeter home for the jmeter utils to load | |
| File jmeterHome = new File("E:\\rivetsys\\servers\\apache-jmeter-2.11\\apache-jmeter-2.11\\apache-jmeter-2.11"); | |
| String slash = System.getProperty("file.separator"); | |
| if (jmeterHome.exists()) { | |
| File jmeterProperties = new File(jmeterHome.getPath() + slash + "bin" + slash + "jmeter.properties"); | |
| if (jmeterProperties.exists()) { | |
| //JMeter Engine | |
| StandardJMeterEngine jmeter = new StandardJMeterEngine(); | |
| //JMeter initialization (properties, log levels, locale, etc) | |
| JMeterUtils.setJMeterHome(jmeterHome.getPath()); | |
| JMeterUtils.loadJMeterProperties(jmeterProperties.getPath()); | |
| JMeterUtils.initLogging();// you can comment this line out to see extra log messages of i.e. DEBUG level | |
| JMeterUtils.initLocale(); | |
| // JMeter Test Plan, basically JOrphan HashTree | |
| HashTree testPlanTree = new HashTree(); | |
| // First HTTP Sampler - open uttesh.com | |
| HTTPSamplerProxy examplecomSampler = new HTTPSamplerProxy(); | |
| examplecomSampler.setDomain("uttesh.com"); | |
| examplecomSampler.setPort(80); | |
| examplecomSampler.setPath("/"); | |
| examplecomSampler.setMethod("GET"); | |
| examplecomSampler.setName("Open uttesh.com"); | |
| examplecomSampler.setProperty(TestElement.TEST_CLASS, HTTPSamplerProxy.class.getName()); | |
| examplecomSampler.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName()); | |
| // Loop Controller | |
| LoopController loopController = new LoopController(); | |
| loopController.setLoops(1); | |
| loopController.setFirst(true); | |
| loopController.setProperty(TestElement.TEST_CLASS, LoopController.class.getName()); | |
| loopController.setProperty(TestElement.GUI_CLASS, LoopControlPanel.class.getName()); | |
| loopController.initialize(); | |
| // Thread Group | |
| ThreadGroup threadGroup = new ThreadGroup(); | |
| threadGroup.setName("Sample Thread Group"); | |
| threadGroup.setNumThreads(1); | |
| threadGroup.setRampUp(1); | |
| threadGroup.setSamplerController(loopController); | |
| threadGroup.setProperty(TestElement.TEST_CLASS, ThreadGroup.class.getName()); | |
| threadGroup.setProperty(TestElement.GUI_CLASS, ThreadGroupGui.class.getName()); | |
| // Test Plan | |
| TestPlan testPlan = new TestPlan("Create JMeter Script From Java Code"); | |
| testPlan.setProperty(TestElement.TEST_CLASS, TestPlan.class.getName()); | |
| testPlan.setProperty(TestElement.GUI_CLASS, TestPlanGui.class.getName()); | |
| testPlan.setUserDefinedVariables((Arguments) new ArgumentsPanel().createTestElement()); | |
| // Construct Test Plan from previously initialized elements | |
| testPlanTree.add(testPlan); | |
| HashTree threadGroupHashTree = testPlanTree.add(testPlan, threadGroup); | |
| threadGroupHashTree.add(examplecomSampler); | |
| // save generated test plan to JMeter's .jmx file format | |
| SaveService.saveTree(testPlanTree, new FileOutputStream("report\\jmeter_api_sample.jmx")); | |
| //add Summarizer output to get test progress in stdout like: | |
| // summary = 2 in 1.3s = 1.5/s Avg: 631 Min: 290 Max: 973 Err: 0 (0.00%) | |
| Summariser summer = null; | |
| String summariserName = JMeterUtils.getPropDefault("summariser.name", "summary"); | |
| if (summariserName.length() > 0) { | |
| summer = new Summariser(summariserName); | |
| } | |
| // Store execution results into a .jtl file, we can save file as csv also | |
| String reportFile = "report\\report.jtl"; | |
| String csvFile = "report\\report.csv"; | |
| ResultCollector logger = new ResultCollector(summer); | |
| logger.setFilename(reportFile); | |
| ResultCollector csvlogger = new ResultCollector(summer); | |
| csvlogger.setFilename(csvFile); | |
| testPlanTree.add(testPlanTree.getArray()[0], logger); | |
| testPlanTree.add(testPlanTree.getArray()[0], csvlogger); | |
| // Run Test Plan | |
| jmeter.configure(testPlanTree); | |
| jmeter.run(); | |
| System.out.println("Test completed. See " + jmeterHome + slash + "report.jtl file for results"); | |
| System.out.println("JMeter .jmx script is available at " + jmeterHome + slash + "jmeter_api_sample.jmx"); | |
| System.exit(0); | |
| } | |
| } | |
| System.err.println("jmeterHome property is not set or pointing to incorrect location"); | |
| System.exit(1); | |
| } | |
| } |
JMETER通过java代码通过代码/ JMETER API实现示例进行负载测试的更多相关文章
- jmeter经验---java 追加写入代码一例
最近最项目参数化的时候用到,场景是这样的,需要测试A和B两个接口,其中B接口传入的参数必须是传递给A接口过的,所以整理一个思路就是: 1. 正常调用A接口,但是将传递给A接口的参数保存到文本里,此处要 ...
- JMeter脚本java代码String数组要写成String[] args,不能写成String args[],否则报错。
JMeter脚本java代码String数组中括号要写在类型关键字后面,不能写在变量名后面.
- jmeter 的java请求代码在main方法里面执行
1.新建一个java请求执行加法类 public class TestDemo { public int Tdemo(int a,int b){ int sum = 0; sum = a+b; ret ...
- 自定义编写jmeter的Java测试代码
我们在做性能测试时,有时需要自己编写测试脚本,很多测试工具都支持自定义编写测试脚本,比如LoadRunner就有很多自定义脚本的协议,比如"C Vuser","JavaV ...
- JMeter扩展Java请求实现WebRTC本地音视频推流压测脚本
WebRTC是Web Real-Time Communication缩写,指网页即时通讯,是一个支持Web浏览器进行实时语音或视频对话的API,实现了基于网页的视频会议,比如声网的Agora Web ...
- Jmeter发送Java请求
1.创建一个Java工程 2.把Jmeter的lib\ext目录下的ApacheJMeter_java.jar.ApacheJMeter_core.jar文件添加进该项目的Build Path 3.创 ...
- jmeter 与 java http
jmeter 如果对java代码进行测试 1.eclips中创建一个项目,且写一个待测试的简单java代码 2.将jmeter路径下 x:\xx\lxx\Dowxxxxxx\apache-jmeter ...
- JMeter学习(十八)JMeter测试Java(二)
实例: 服务为:将输入的两个参数通过IO存入文件: 1.打开MyEclipse,编写Java代码 服务: package test; import java.io.File; import java. ...
- 【转】jmeter 进行java request测试
本周使用jmeter进行一个远程dubbo接口的性能测试,因为没有访问页面,本来开发可以写一个页面,进行http请求的调用,不过已经看到jmeter可以直接对java request进行测试,所以尝试 ...
随机推荐
- go 文件上传
package main import ( "fmt" "io" "io/ioutil" "log" "net ...
- 自动化测试框架selenium+java+TestNG——TestNG注解、执行、测试结果和测试报告
TestNG是java的一个测试框架,相比较于junit,功能更强大和完善,我是直接学习和使用的TestNG就来谈下TestNG的一些特点吧. TestNG的特点 注解 TestNG使用Java和面向 ...
- ansible使用中遇到的问题
前提是,可以ssh无秘钥过去,但是使用ansible就报这个错误, 正在找造成的原因及解决方法 第一步, 明白了,,如何已经打通ssh无秘钥后,就不能再 hosts中加入ansible_ssh_pas ...
- hdu 1106 排序 解题报告
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1106 这个题目一开始以为是水题,就想着用来轻松轻松,谁知道改得我想吐!! 除了discuss 中的数据 ...
- C和C++语言&
#include "stdafx.h"#include "iostream"#include "animal.h"using namespa ...
- nvidia-smi 查看GPU信息字段解读
第一栏的Fan:N/A是风扇转速,从0到100%之间变动,这个速度是计算机期望的风扇转速,实际情况下如果风扇堵转,可能打不到显示的转速.有的设备不会返回转速,因为它不依赖风扇冷却而是通过其他外设保持低 ...
- HDU1711(KMP入门题)
Number Sequence Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) ...
- force
题意 求解 Ei = Fi/qi 解法: 方法一: 考虑左侧的式子,直接多项式乘法. 对于右面的式子,我们记做$B_j$,这样有 $$B_j = \sum_{j<i}{ revq_{n-i} f ...
- CodeForces 1091G. New Year and the Factorisation Collaboration
题目简述:若你获得“超能力”:固定$n$,对任意$a$,可以快速求出$x \in [0, n)$(若存在),使得$x^2 \equiv a \pmod n$,若存在多个$x$满足条件,则返回其中一个( ...
- idea2018.2.5版本使用之背景色
idea 背景色: 写代码区换眼色豆沙色: