全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-18 10 分钟 ✍️ juanwangdev

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支持弱高并发测试
heyGo原生、易用功能较简单快速测试
ab广泛使用单线程简单测试
Vegeta报告丰富配置复杂详细分析

注意:压力测试应在独立环境进行,避免影响生产服务。

要点总结

  1. wrk:高性能多线程,支持 Lua 脚本自定义请求
  2. hey:Go原生工具,简单易用
  3. ab:经典工具,广泛使用
  4. Vegeta:报告丰富,支持图形化
  5. 关键指标:QPS、延迟、错误率
  6. 渐进测试:从低并发逐步增加,观察拐点

📝 发现内容有误?点击此处直接编辑

← 上一篇 Gin 单元测试编写
下一篇 → Gin 性能测试与基准测试
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库