您现在的位置是:网站首页 > 压测工具使用文章详情
压测工具使用
陈川
【
Node.js
】
18709人已围观
3947字
压测工具的基本概念
压测工具用于模拟大量用户请求,测试系统在高并发场景下的性能表现。Node.js生态中有多种压测工具,比如artillery
、loadtest
、k6
等。这些工具可以帮助开发者发现系统瓶颈,优化性能。
// 一个简单的HTTP服务器示例
const http = require('http');
const server = http.createServer((req, res) => {
res.end('Hello World');
});
server.listen(3000);
artillery的使用方法
artillery是一个流行的Node.js压测工具,支持HTTP和WebSocket协议。安装方式很简单:
npm install -g artillery
基础测试脚本通常写成YAML格式:
config:
target: "http://localhost:3000"
phases:
- duration: 60
arrivalRate: 10
scenarios:
- flow:
- get:
url: "/"
运行测试命令:
artillery run test.yml
高级压测场景配置
artillery支持更复杂的测试场景,比如:
- 多阶段压力测试:
phases:
- duration: 30
arrivalRate: 5
name: "预热阶段"
- duration: 60
arrivalRate: 20
name: "压力测试"
- duration: 30
arrivalRate: 5
name: "冷却阶段"
- 带认证的请求:
scenarios:
- flow:
- post:
url: "/login"
json:
username: "test"
password: "123456"
- get:
url: "/profile"
结果分析与可视化
artillery生成的JSON报告可以转换为HTML:
artillery report result.json
关键指标包括:
- 请求成功率
- 响应时间分布
- 吞吐量(RPS)
- 错误率
loadtest的快速使用
另一个轻量级工具loadtest适合快速测试:
npm install -g loadtest
基本用法:
loadtest -n 1000 -c 100 http://localhost:3000/
常用参数:
-n
: 总请求数-c
: 并发数--rps
: 每秒请求数限制
k6的现代化方案
k6是一个更现代的压测工具,使用Go编写但支持JS脚本:
import http from 'k6/http';
import { check, sleep } from 'k6';
export let options = {
vus: 100,
duration: '30s',
};
export default function() {
let res = http.get('http://localhost:3000');
check(res, {
'status is 200': (r) => r.status === 200,
});
sleep(1);
}
运行命令:
k6 run script.js
真实场景的压测技巧
- 测试数据库密集型应用时,注意准备测试数据:
// 使用artillery的beforeRequest钩子
scenarios:
- beforeRequest: "generateData"
flow:
- post:
url: "/api/data"
json:
id: "{{ id }}"
value: "{{ randomValue }}"
- 分布式压测:
# 使用artillery的worker模式
artillery run --workers 4 --count 10 test.yml
- 监控系统资源:
# 结合top或htop观察CPU/内存使用
top -pid $(pgrep -n node)
常见问题排查
- 端口耗尽问题:
# 查看当前连接数
netstat -an | grep ESTABLISHED | wc -l
# 增加系统限制
sysctl -w net.ipv4.ip_local_port_range="1024 65535"
- 内存泄漏检测:
// 在Node.js中定期记录内存使用
setInterval(() => {
console.log(process.memoryUsage());
}, 1000);
- 错误处理示例:
scenarios:
- flow:
- get:
url: "/"
capture:
- json: "$.error"
as: "apiError"
- log: "Error was {{ apiError }}"
性能优化建议
- 连接池配置示例:
const http = require('http');
const agent = new http.Agent({
keepAlive: true,
maxSockets: 100
});
http.get({
hostname: 'localhost',
port: 3000,
agent: agent
}, (res) => {});
- 集群模式启动Node服务:
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
} else {
require('./server');
}
- 使用Redis缓存:
const redis = require('redis');
const client = redis.createClient();
app.get('/data', (req, res) => {
client.get('cachedData', (err, reply) => {
if (reply) return res.send(reply);
// 否则从数据库获取
});
});
持续集成中的压测
在CI管道中加入压测步骤:
# .github/workflows/loadtest.yml
name: Load Test
on: [push]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- run: npm install -g artillery
- run: artillery run test.yml
env:
CI: true
安全注意事项
- 不要对生产环境直接压测:
config:
target: "http://staging.example.com"
# 而不是 production.example.com
- 限制测试范围:
phases:
- duration: 10
arrivalRate: 1
# 先用低负载验证测试脚本
- 监控系统告警:
# 设置CPU使用率监控
mpstat 1 10 | awk '$12 < 10 {print "CPU overload"}'