JMeter官网下载一个JMeter绿包,根据自身的操作系统来选择包,本文主要以Windows操作系统为例。

将下载好的包放置本地磁盘中,建议放在系统盘以外的其他盘符,防止出现文件读写权限问题。

示例代码:

/**
 * 执行Jmeter
 * @Param jmeterParam为参数实体,其中包含网络请求的url、method等参数
 * @Param jmeterHomePath为本地Jemter地址,如本机D:\apache-jmeter-5.5\
 * */
public void runJmeter(JmeterParam jmeterParam) throws IOException, InterruptedException {

    String data="";
    File jmeterHome = new File(jmeterHomePath);
    // 分隔符
    String slash = System.getProperty("file.separator");
    try{
        //判断jmeterHome
        if (jmeterHome.exists()) {
            File jmeterProperties = new File(jmeterHome.getPath() + slash + "bin" + slash + "jmeter.properties");
            if (jmeterProperties.exists()) {

                // 初始化压测引擎
                StandardJMeterEngine jmeter = new StandardJMeterEngine();
                // JMeter初始化(属性、日志级别、区域设置等)
                JMeterUtils.setJMeterHome(jmeterHome.getPath());
                JMeterUtils.loadJMeterProperties(jmeterProperties.getPath());
                JMeterUtils.initLogging();
                JMeterUtils.initLocale();

                // JMeter测试计划
                HashTree testPlanTree = new HashTree();

                //开始组装HashTree
                URL uri = new URL(jmeterParam.getUrl());
                String protocol = uri.getProtocol();
                String host = uri.getHost();
                String path = uri.getPath();
                String query = uri.getQuery();
                String method = jmeterParam.getMethod();
                int port = uri.getPort();  //需要额外处理,测试的时候取出来,有-1的情况

                if(port == -1){
                    if("http".equals(protocol)){
                        port = 80;
                    }
                    if("https".equals(protocol)){
                        port = 443;
                    }
                }
                HTTPSamplerProxy httpSamplerProxy = new HTTPSamplerProxy();
                httpSamplerProxy.setDomain(host);
                httpSamplerProxy.setPort(port);
                if(Objects.nonNull(query) && !"".equals(query)){
                    httpSamplerProxy.setPath(path + "?" + query);
                }else{
                    httpSamplerProxy.setPath(path); //路径
                }
                httpSamplerProxy.setMethod(method);
                httpSamplerProxy.setName("JmeterTest"+System.currentTimeMillis());
                httpSamplerProxy.setProperty(TestElement.TEST_CLASS, HTTPSamplerProxy.class.getName());
                httpSamplerProxy.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName());

                // Loop Controller 循环控制
                LoopController loopController = new LoopController();
                loopController.setLoops(jmeterParam.getLoops());
                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("ThreadGroup");
                threadGroup.setNumThreads(jmeterParam.getThreads());
                threadGroup.setRampUp(jmeterParam.getRampUp());
                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("JMeterPlan");
                testPlan.setProperty(TestElement.TEST_CLASS, TestPlan.class.getName());
                testPlan.setProperty(TestElement.GUI_CLASS, TestPlanGui.class.getName());
                testPlan.setUserDefinedVariables((Arguments) new ArgumentsPanel().createTestElement());

                // 从以上初始化的元素构造测试计划
                testPlanTree.add(testPlan);
                HashTree threadGroupHashTree = testPlanTree.add(testPlan, threadGroup);
                threadGroupHashTree.add(httpSamplerProxy);
                String jmeterTestName= UUID.randomUUID().toString();

                String savePath= this.getClass().getClassLoader().getResource("static").getPath()+"/jmeter/jmx/";
                File jmxPath = new File(savePath);
                if (!jmxPath.exists()) {
                    jmxPath.mkdirs();
                }
                logger.info("路径为:"+savePath);
                // 将生成的测试计划保存为JMeter的.jmx文件格式
                SaveService.saveTree(testPlanTree, new FileOutputStream(savePath + jmeterTestName+".jmx"));

                // 在stdout中添加summary输出,得到测试进度,如:
                // 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);
                }

                // 将执行结果存储到.jtl文件中
                String logFile = savePath + jmeterTestName+".jtl";
                ResultCollector resultCollector = new ResultCollector(summer);
                resultCollector.setFilename(logFile);
                testPlanTree.add(testPlanTree.getArray()[0], resultCollector);

                logger.info("执行的测试结果为:"+ JSONObject.valueToString(resultCollector));

                // 单机执行测试计划
                jmeter.configure(testPlanTree);  // 设置回调监听器,并添加状态
                jmeter.run();

                //调用命令生成jmeter -g D:\apache-jmeter-5.5\example.jtl -o D:\apache-jmeter-5.5\ResultReport
                StringBuilder command = new StringBuilder();
                //此代码块是为了Windows环境正常执行,研发环境可忽略
                if (Objects.equals(File.separator, "\\")) {
                    command.append("cmd.exe /c ");
                }
                String reportPath=this.getClass().getClassLoader().getResource("static").getPath()+"/jmeter/report/"+jmeterTestName+"/";
                File f_1 = new File(reportPath);
                if (!f_1.exists()) {
                    f_1.mkdirs();
                }
                command.append(jmeterHomePath+File.separator+"bin").append(File.separator).append("jmeter -g ").append(logFile).append(" -o ").append(reportPath);
                logger.info("{}", command.toString());
                // 等待执行完成
                Runtime.getRuntime().exec(command.toString()).waitFor();
                String sourcePath=this.getClass().getClassLoader().getResource("static").getPath()+"/jmeter/report/"+jmeterTestName;
                String zipPath=this.getClass().getClassLoader().getResource("static").getPath()+"/jmeter/report/"+jmeterTestName+".zip";
                ZipTools.toZip(zipPath,sourcePath,true);
                //zipPath为压缩后的报告所在地址
            }
        }
    }catch (Exception e){
        e.printStackTrace();
    }
    result.put("code",code);
    result.put("msg",msg);
    result.put("data",data);
    return result;
}

以上为基础的JMeterAPI使用方法。