一、容量评估概述
系统容量评估是架构设计的核心:
容量评估目标:
- 确定系统最大承载能力
- 指导服务器数量规划
- 提前发现性能瓶颈
二、容量评估方法
1. 评估模型
系统容量 = 并发用户数 × 每用户请求数 × 平均响应时间
QPS = (PV / 峰值系数) / (86400 × 峰值时间占比)
2. 评估公式
java
public class CapacityCalculator {
// 评估需要的服务器数量
public static int calculateServerCount(
long dailyPV, // 日PV
double peakFactor, // 峰值系数(通常2-3)
int avgResponseTime, // 平均响应时间(ms)
int maxQPSPerServer // 单机最大QPS
) {
// 计算峰值QPS
long peakQPS = (long) (dailyPV * peakFactor / 86400);
// 计算服务器数量(考虑冗余)
double serverCount = (double) peakQPS / maxQPSPerServer * 1.3;
return (int) Math.ceil(serverCount);
}
// 评估带宽需求
public static long calculateBandwidth(
long peakQPS,
int avgRequestSize // 字节
) {
return peakQPS * avgRequestSize * 8 / 1024 / 1024; // Mbps
}
}
3. 容量评估示例
场景:电商系统
- 日PV:100万
- 峰值系数:3
- 峰值QPS:100万 × 3 / 86400 ≈ 35
- 单机QPS:5000
- 所需服务器:35 / 5000 × 1.3 ≈ 1台
实际需要考虑:
- 突发流量(峰值可能是平均的5-10倍)
- 冗余(至少2台)
- 降级方案
三、压测工具对比
1. JMeter
特点:
- 开源免费
- 图形化界面
- 丰富的协议支持
- 适合复杂场景
bash
# 命令行运行
jmeter -n -t test.jmx -l results.jtl -e -o report/
2. wrk
特点:
- 轻量级,高性能
- 支持Lua脚本
- 仅支持HTTP
bash
# 简单压测
wrk -t12 -c400 -d30s http://localhost:8080/api
# 使用脚本
wrk -t4 -c100 -d30s -s post.lua http://localhost:8080/api
3. Gatling
特点:
- Scala编写
- 代码化脚本
- 详细报告
scala
// Scala脚本
class LoadSimulation extends Simulation {
val httpProtocol = http
.baseUrl("http://localhost:8080")
val scn = scenario("UserFlow")
.exec(http("Home").get("/"))
.exec(http("Products").get("/api/products"))
setUp(scn.inject(rampUsers(1000).during(60)))
.protocols(httpProtocol)
}
4. 工具对比
| 工具 | 性能 | 易用性 | 协议支持 | 报告 | 适用场景 |
|---|---|---|---|---|---|
| JMeter | 中 | 高 | 丰富 | 中 | 复杂场景 |
| wrk | 高 | 中 | 仅HTTP | 简单 | 简单压测 |
| Gatling | 高 | 中 | 丰富 | 详细 | 高并发 |
| Locust | 高 | 高 | 丰富 | 中 | Python项目 |
四、压测实践
1. 压测流程
1. 准备测试环境
2. 设计测试场景
3. 执行压测
4. 分析结果
5. 优化瓶颈
6. 验证优化效果
2. 压测场景设计
yaml
# 压测场景
scenarios:
- name: "正常流量"
weight: 70
requests:
- get /product/list
- get /product/detail
- name: "下单流程"
weight: 20
requests:
- post /cart/add
- post /order/create
- name: "搜索"
weight: 10
requests:
- get /search
3. 结果分析
压测指标:
- QPS:每秒请求数
- 响应时间:P50/P90/P99
- 错误率:失败请求比例
- 资源使用:CPU/内存/IO
五、总结
容量评估与压测是保障系统稳定性的关键:
- 容量评估:计算所需资源
- 压测验证:验证系统能力
- 工具选择:根据场景选择
个人观点,仅供参考