通过Java执行JMeter脚本

q5iwbnjs  于 2022-11-09  发布在  Java
关注(0)|答案(1)|浏览(288)

我需要通过命令提示符执行一组JMeter脚本。
流:

需要通过Java代码执行相同的操作。即Java程序应打开命令提示符并执行上述步骤?
注意:执行流程批次档案不是有效的选项。它会耗用操作系统内存。

jm2pwxwz

jm2pwxwz1#

虽然it's possible to run JMeter script using Java code通过JMeter API使用的代码像:

import org.apache.jmeter.engine.StandardJMeterEngine;
import org.apache.jmeter.report.dashboard.ReportGenerator;
import org.apache.jmeter.reporters.ResultCollector;
import org.apache.jmeter.reporters.Summariser;
import org.apache.jmeter.save.SaveService;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.collections.HashTree;

import java.io.File;

public class JMeterTestRunner {

    public static void main(String[] args) throws Exception {
        // JMeter Engine
        StandardJMeterEngine jmeter = new StandardJMeterEngine();

        // Initialize Properties, logging, locale, etc.
        JMeterUtils.loadJMeterProperties("c:/path/to/your/jmeter/bin/jmeter.properties");
        JMeterUtils.setJMeterHome("c:/path/to/your/jmeter");
        JMeterUtils.initLocale();

        // Initialize JMeter SaveService
        SaveService.loadProperties();

        // Load existing .jmx Test Plan
        HashTree testPlanTree = SaveService.loadTree(new File("/path/to/your/test.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
        String logFile = "/path/to/test/result.jtl";
        ResultCollector logger = new ResultCollector(summer);
        logger.setFilename(logFile);
        testPlanTree.add(testPlanTree.getArray()[0], logger);

        // Run JMeter Test
        jmeter.configure(testPlanTree);
        jmeter.run();

        // Generate HTML Report Dashboard
        ReportGenerator generator = new ReportGenerator(logFile, null);
        generator.generate();

    }
}

我不认为资源占用会更少,因为CMD的示例占用的资源比Java运行时少很多
如果您的系统由于高资源使用率而无法运行JMeter测试,首先检查您是否遵循JMeter Best Practices,如果是,并且资源消耗仍然很高-您将不得不找到另一台机器和run JMeter in distributed mode

相关问题