Gatling:基于Scala的高性能负载测试工具
一、Gatling 简介
Gatling 是一个开源的 HTTP 压力测试工具,专为高并发场景设计,支持 HTTP/HTTPS、WebSocket、Kafka 等协议。其基于 Scala 的脚本语法简洁高效,支持实时报告生成和分布式测试。
核心特性:
- 轻量级:无 GUI,通过代码脚本定义测试场景
- 高性能:支持每秒数万次请求
- 实时监控:基于 HTML 的动态报告
- 协议扩展:支持自定义 DSL 和插件
二、安装指南
1. 基于 SBT 安装(推荐)
# 下载 Gatling 最新版本
wget https://repo1.maven.org/maven2/io/gatling/highcharts/gatling.highcharts_2.13/3.7.0/gatling.highcharts_2.13-3.7.0.zip# 解压并进入目录
unzip gatling.highcharts_2.13-3.7.0.zip
cd gatling.highcharts_2.13-3.7.0# 启动 Gatling
bin/gatling.sh -s your_test_script.scala
2. Docker 快速启动
docker run -d -p 8080:8080 denvazh/gatling
三、基础使用说明
1. 编写测试脚本
示例脚本(BasicSimulation.scala
):
import io.gatling.core.Predef._
import io.gatling.http.Predef._class BasicSimulation extends Simulation {val httpProtocol = http.baseUrl("https://example.com")val scn = scenario("Basic Test").exec(http("Request Page").get("/"))setUp(scn.inject(atOnceUsers(100))).protocols(httpProtocol)
}
2. 执行测试
# 运行测试并生成报告
bin/gatling.sh -s BasicSimulation.scala -rf report -of html# 查看实时报告
open report/index.html
3. 结果分析
关键指标:
指标 | 说明 |
---|---|
Requests per second | 每秒请求数(RPS) |
Average response time | 平均响应时间(ms) |
Error rate | 错误率 |
四、高级配置
1. 参数化测试数据
使用 CSV 文件:
val feeder = csv("user_data.csv")exec(http("Login").post("/login").body(StringBodyFromFile("data/${username}")).asJson)
2. 分布式测试
启动 Master 节点:
bin/gatling.sh -master -localPort 26201 -remotePort 26202
启动 Slave 节点:
bin/gatling.sh -slave -masterHost master_ip -masterPort 26201
五、典型应用场景
-
Web API 性能测试
- 模拟高并发用户访问电商网站
- 验证限时抢购接口稳定性
-
微服务压力测试
- 测试 Kafka 消息队列吞吐量
- 验证 gRPC 服务在高负载下的表现