Gin 压力测试工具使用
压力测试用于评估 API 在高并发下的性能表现,是上线前的重要验证步骤。
wrk 工具
安装 wrk
Bash
# Windows (使用预编译版本或 Git Bash)
# Linux/Mac
git clone https://github.com/wg/wrk.git
cd wrk && make
基本用法
Bash
# 基本测试
wrk -t4 -c100 -d30s http://localhost:8080/api/data
# 参数说明
# -t4 : 4个线程
# -c100 : 100个连接
# -d30s : 持续30秒
# 输出示例
Running 30s test @ http://localhost:8080/api/data
4 threads and 100 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 15.32ms 10.21ms 50.00ms 75.00%
Req/Sec 6.5k 1.2k 8.0k 70.00%
Latency Distribution
50% 12.00ms
75% 18.00ms
90% 25.00ms
99% 40.00ms
780000 requests in 30.00s, 156.00MB read
Requests/sec: 26000.00
Transfer/sec: 5.20MB
使用 Lua 脚本
lua
-- post.lua
wrk.method = "POST"
wrk.body = '{"name":"test","email":"test@example.com"}'
wrk.headers["Content-Type"] = "application/json"
wrk.headers["Authorization"] = "Bearer token123"
-- 自定义请求
request = function()
local id = math.random(1, 10000)
return wrk.format("GET", "/api/users/" .. id)
end
-- 响应处理
response = function(status, headers, body)
if status ~= 200 then
print("Error: " .. status)
end
end
-- 统计处理
done = function(summary, latency, requests)
print("Total requests: " .. summary.requests)
print("Avg latency: " .. latency.mean .. "ms")
end
Bash
# 使用 Lua 脚本
wrk -t4 -c100 -d30s -s post.lua http://localhost:8080/api/users
hey 工具
安装 hey
Bash
go install github.com/rakyll/hey@latest
基本用法
Bash
# 基本测试
hey -n 1000 -c 100 http://localhost:8080/api/data
# 参数说明
# -n 1000 : 总请求数
# -c 100 : 并发数
# -q 10 : 每个 worker 每秒请求数限制(可选)
# POST 请求
hey -n 1000 -c 100 -m POST -d '{"name":"test"}' \
-H "Content-Type: application/json" \
http://localhost:8080/api/users
# 输出更详细的统计
hey -n 10000 -c 200 -o csv http://localhost:8080/api/data > results.csv
hey 输出分析
Bash
Summary:
Total: 2.5 secs
Slowest: 0.05 secs
Fastest: 0.01 secs
Average: 0.02 secs
Requests/sec: 4000.00
Response time histogram:
0.010 [1000]
0.020 [3000]
0.030 [2000]
0.040 [500]
0.050 [500]
Status code distribution:
[200] 10000 responses
ab (Apache Bench)
安装 ab
Bash
# Windows: Apache 安装目录自带
# Linux: apt install apache2-utils
# Mac: 自带
基本用法
Bash
# 基本测试
ab -n 1000 -c 100 http://localhost:8080/api/data
# 参数说明
# -n 1000 : 总请求数
# -c 100 : 并发数
# -k : 保持连接(Keep-Alive)
# POST 请求
ab -n 1000 -c 100 -p data.json -T "application/json" \
http://localhost:8080/api/users
# 输出分析
Requests per second: 5000.21 [#/sec] (mean)
Time per request: 20.000 [ms] (mean)
Time per request: 0.200 [ms] (mean, across all concurrent requests)
Transfer rate: 100.50 [Kbytes/sec] received
go-wrk
安装 go-wrk
Bash
go install github.com/adjust/go-wrk@latest
基本用法
Bash
go-wrk -c 100 -n 1000 -t 4 http://localhost:8080/api/data
# 输出
1000 requests in 0.5s, 50KB read
Requests/sec: 2000
Latency: 10ms (avg), 5ms (min), 50ms (max)
Vegeta
安装 Vegeta
Bash
go install github.com/tsenart/vegeta@latest
基本用法
Bash
# 基本攻击
vegeta attack -duration=30s -rate=100 -targets=targets.txt > results.bin
# targets.txt 内容
GET http://localhost:8080/api/data
POST http://localhost:8080/api/users
@body.json
# 查看报告
vegeta report results.bin
# 输出
Requests [total, rate] 3000, 100.00
Duration [total, attack, wait] 30s, 30s, 0s
Latencies [mean, 50, 90, 99, max] 15ms, 10ms, 25ms, 40ms, 50ms
Bytes In [total, mean] 150KB, 50B
Bytes Out [total, mean] 0, 0B
Success [ratio] 100.00%
Status Codes [code:count] 200:3000
Vegeta 图形化报告
Go
# 生成 HTML 报告
vegeta report -type=html results.bin > report.html
# 生成时序图
vegeta plot results.bin > plot.html
Gin 服务压力测试
测试场景配置
Bash
// main.go
func main() {
gin.SetMode(gin.TestMode)
r := gin.New()
r.GET("/api/simple", func(c *gin.Context) {
c.String(200, "ok")
})
r.GET("/api/json", func(c *gin.Context) {
c.JSON(200, gin.H{"status": "ok"})
})
r.GET("/api/db", func(c *gin.Context) {
// 模拟数据库查询
time.Sleep(10 * time.Millisecond)
c.JSON(200, gin.H{"data": "result"})
})
r.POST("/api/create", func(c *gin.Context) {
var data map[string]string
c.ShouldBindJSON(&data)
c.JSON(201, gin.H{"id": 123})
})
r.Run(":8080")
}
测试脚本
Bash
#!/bin/bash
echo "=== 测试简单响应 ==="
wrk -t4 -c100 -d10s http://localhost:8080/api/simple
echo "=== 测试 JSON 响应 ==="
wrk -t4 -c100 -d10s http://localhost:8080/api/json
echo "=== 测试模拟数据库查询 ==="
wrk -t4 -c50 -d10s http://localhost:8080/api/db
echo "=== 测试 POST 请求 ==="
wrk -t4 -c100 -d10s -s post.lua http://localhost:8080/api/create
性能指标分析
关键指标
| 指标 | 说明 | 健康范围 |
|---|---|---|
| Requests/sec | 每秒请求数 | 根据业务需求 |
| Latency (avg) | 平均延迟 | < 100ms |
| Latency (99%) | 99%延迟 | < 500ms |
| Error rate | 错误率 | < 1% |
命令行一键测试
Bash
#!/bin/bash
# stress_test.sh
URL=$1
DURATION=${2:-30s}
CONNECTIONS=${3:-100}
echo "Testing: $URL"
echo "Duration: $DURATION"
echo "Connections: $CONNECTIONS"
wrk -t4 -c$CONNECTIONS -d$DURATION --latency $URL
# 同时采集 profile
curl "${URL}:8080/debug/pprof/profile?seconds=30" > cpu.prof
# 分析
go tool pprof -top cpu.prof
渐进式压力测试
Bash
# 从低并发开始逐步增加
# 50 连接
wrk -t2 -c50 -d30s http://localhost:8080/api/data
# 100 连接
wrk -t4 -c100 -d30s http://localhost:8080/api/data
# 200 连接
wrk -t8 -c200 -d30s http://localhost:8080/api/data
# 500 连接
wrk -t12 -c500 -d30s http://localhost:8080/api/data
# 观察性能拐点
结果对比分析
text
# 多次测试对比
wrk -t4 -c100 -d30s http://localhost:8080/api/data > baseline.txt
# 优化后测试
wrk -t4 -c100 -d30s http://localhost:8080/api/data > optimized.txt
# 对比
diff baseline.txt optimized.txt
工具对比
| 工具 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|
| wrk | 高性能、Lua脚本 | Windows支持弱 | 高并发测试 |
| hey | Go原生、易用 | 功能较简单 | 快速测试 |
| ab | 广泛使用 | 单线程 | 简单测试 |
| Vegeta | 报告丰富 | 配置复杂 | 详细分析 |
注意:压力测试应在独立环境进行,避免影响生产服务。
要点总结
- wrk:高性能多线程,支持 Lua 脚本自定义请求
- hey:Go原生工具,简单易用
- ab:经典工具,广泛使用
- Vegeta:报告丰富,支持图形化
- 关键指标:QPS、延迟、错误率
- 渐进测试:从低并发逐步增加,观察拐点
📝 发现内容有误?点击此处直接编辑