负载测试与压力测试
测试类型
| 类型 |
目的 |
| 负载测试 |
测试系统在预期负载下的表现 |
| 压力测试 |
测试系统在超出负载时的行为 |
| 浸泡测试 |
测试系统长时间运行的稳定性 |
| 尖峰测试 |
测试系统应对突发流量的能力 |
Apache Bench (ab)
# 基本用法
ab -n 10000 -c 100 http://localhost/
# 参数说明
# -n: 总请求数
# -c: 并发数
# -t: 超时时间
# -p: POST数据文件
# -T: Content-Type
# 示例
ab -n 10000 -c 200 -t 60 http://localhost/api
wrk
# 安装
git clone https://github.com/wg/wrk.git
cd wrk && make
# 基本用法
wrk -t4 -c100 -d30s http://localhost/
# 参数说明
# -t: 线程数
# -c: 连接数
# -d: 持续时间
# -s: Lua脚本
# 使用Lua脚本
wrk -t4 -c100 -d30s -s post.lua http://localhost/api
Lua脚本示例
-- post.lua
wrk.method = "POST"
wrk.body = '{"username": "test", "password": "test"}'
wrk.headers["Content-Type"] = "application/json"
JMeter
<!-- 测试计划示例 -->
<TestPlan>
<ThreadGroup>
<numThreads>100</numThreads>
<rampTime>60</rampTime>
<loopCount>1000</loopCount>
<HTTPSampler>
<domain>localhost</domain>
<port>80</port>
<path>/api</path>
<method>GET</method>
</HTTPSampler>
</ThreadGroup>
</TestPlan>
k6
// load-test.js
import http from 'k6/http';
import { check, sleep } from 'k6';
export let options = {
stages: [
{ duration: '30s', target: 20 },
{ duration: '1m', target: 20 },
{ duration: '30s', target: 100 },
{ duration: '1m', target: 100 },
{ duration: '30s', target: 0 },
],
};
export default function () {
let res = http.get('http://localhost/api');
check(res, {
'status is 200': (r) => r.status === 200,
'response time < 500ms': (r) => r.timings.duration < 500,
});
sleep(1);
}
实践:完整测试脚本
#!/bin/bash
URL="http://localhost"
ENDPOINTS=("/" "/api/users" "/api/products")
echo "=== 负载测试 ==="
for endpoint in "${ENDPOINTS[@]}"; do
echo ""
echo "测试端点: $endpoint"
echo "-------------------"
# 使用wrk测试
wrk -t4 -c50 -d30s "${URL}${endpoint}"
echo ""
done
echo ""
echo "=== 压力测试 ==="
# 递增并发数测试
for c in 10 50 100 200 500; do
echo ""
echo "并发数: $c"
echo "-------------------"
wrk -t4 -c$c -d10s "${URL}/"
done
测试报告
# 使用Apache Bench生成报告
ab -n 10000 -c 100 -g results.tsv http://localhost/
# 使用Gnuplot生成图表
gnuplot << 'EOF'
set terminal png size 800,600
set output 'performance.png'
set title 'Performance Test Results'
set xlabel 'Time (s)'
set ylabel 'Requests per Second'
plot 'results.tsv' using 9 title 'RPS'
EOF
性能指标
| 指标 |
说明 |
| 吞吐量 (RPS) |
每秒请求数 |
| 响应时间 |
平均、P95、P99 |
| 错误率 |
失败请求百分比 |
| 并发用户 |
系统支持的最大并发数 |
总结
负载测试是确保系统性能的重要手段。通过定期测试,可以发现性能瓶颈,优化系统配置,确保系统能够应对生产环境的流量。