You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Java版Gatling DSL编写可运行测试?有没有相关参考示例代码?

Gatling Java DSL 实用示例

前置依赖配置(Maven)

<dependencies>
    <dependency>
        <groupId>io.gatling.highcharts</groupId>
        <artifactId>gatling-charts-highcharts</artifactId>
        <version>3.9.5</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.gatling</groupId>
        <artifactId>gatling-app</artifactId>
        <version>3.9.5</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.gatling</groupId>
        <artifactId>gatling-java</artifactId>
        <version>3.9.5</version>
        <scope>test</scope>
    </dependency>
</dependencies>

完整压测示例代码

import io.gatling.javaapi.core.ScenarioBuilder;
import io.gatling.javaapi.core.Simulation;
import io.gatling.javaapi.http.HttpProtocolBuilder;

import static io.gatling.javaapi.core.CoreDsl.*;
import static io.gatling.javaapi.http.HttpDsl.http;
import static io.gatling.javaapi.http.HttpDsl.status;

public class CustomHttpSimulation extends Simulation {

    // 公共HTTP协议配置
    HttpProtocolBuilder httpProtocol = http
            .baseUrl("https://your-test-server.com")
            .acceptHeader("application/json")
            .userAgentHeader("Gatling-Test-Agent");

    // 压测场景定义
    ScenarioBuilder testScenario = scenario("用户接口全链路压测")
            // 第一步:调用查询接口
            .exec(http("get-user-info")
                    .get("/api/user/123")
                    .check(status().is(200))
                    .check(jsonPath("$.data.username").is("testUser"))
            )
            // 模拟用户操作间隔1秒
            .pause(1)
            // 第二步:调用提交接口
            .exec(http("create-user-order")
                    .post("/api/order")
                    .body(StringBody("{\"goodsId\":1001,\"count\":2}"))
                    .asJson()
                    .check(status().is(200))
                    .check(jsonPath("$.code").ofInt().is(0))
            );

    {
        // 压测流量策略:10秒内爬升200个并发用户,持续跑压测3分钟
        setUp(
                testScenario.injectOpen(rampUsers(200).during(10))
        ).protocols(httpProtocol)
                // 全局性能断言
                .assertions(
                        global().successfulRequests().percent().gte(99.9),
                        global().responseTime().percentile95().lt(300)
                );
    }
}

核心注意事项

  • DSL方法全部从io.gatling.javaapi包下静态导入,不要混用Scala版本的Gatling包
  • 最低支持JDK 8,推荐使用JDK 11及以上版本获得更高压测性能
  • 测试可通过mvn gatling:test命令执行,也可直接在IDE中运行Simulation类启动
  • 并发数、压测时长、断言阈值均可根据实际测试需求调整

内容的提问来源于stack exchange,提问作者paul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 01:57:03