负载测试
一句话解释
负载测试模拟真实用户流量,检查系统是否能处理预期负载——响应时间、吞吐量、错误率。
用大白话说
负载测试回答:「我们的系统能处理预期的流量吗?」它模拟真实的用户负载并测量性能指标。负载测试测量什么:1. 响应时间——负载下系统响应速度
- 吞吐量——系统每秒能处理的请求数
- 错误率——负载下失败请求的百分比
- 资源使用——CPU、内存、数据库连接等负载测试类型:1. 基线——正常预期流量
- 峰值——最高预期流量(黑色星期五、产品发布)
- 容量——大量数据,不一定高并发
- 耐久——长时间持续负载(见浸泡测试)
流程:1. 定义测试场景(用户旅程,不只是 API 调用)
- 逐步增加负载到目标水平
- 测试期间监控系统指标
- 识别瓶颈(数据库、CPU、内存、网络)
- 优化并重新测试工具:k6、JMeter、Locust、Artillery、Gatling。
示例
javascript
// k6 load test script
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
stages: [
{ duration: '2m', target: 100 }, // ramp up to 100 users
{ duration: '5m', target: 100 }, // stay at 100 users
{ duration: '2m', target: 200 }, // ramp up to 200 users
{ duration: '5m', target: 200 }, // stay at 200 users
{ duration: '2m', target: 0 }, // ramp down to 0
],
thresholds: {
http_req_duration: ['p(95)<500'], // 95% of requests < 500ms
http_req_failed: ['rate<0.01'], // < 1% errors
},
};
export default function () {
const res = http.get('https://api.example.com/products');
check(res, {
'status is 200': (r) => r.status === 200,
'has products': (r) => r.json().length > 0,
});
sleep(1); // think time between requests
}k6 逐步增加用户,发送请求,检查阈值。如果第 95 百分位响应时间超过 500ms 或错误率超过 1%,测试失败。
常见混淆
容易混淆的对象: stress testing
关键区别: 负载测试模拟预期流量验证系统能处理——测试正常/峰值条件。压力测试推超预期限制找断点——测试故障条件。负载测试问「能处理我们的流量吗」;压力测试问「什么时候会崩溃」。
相关术语
相关资源
相关课程
- Performance Testing
负载测试。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。