使用k6进行性能测试示例

以下是一个使用 k6 对 Node.js 项目进行性能测试的详细示例:


1. 安装 k6

1
2
3
4
5
6
7
8
# macOS (Homebrew)
brew install k6

# Linux (Debian/Ubuntu)
sudo apt-get update && sudo apt-get install k6

# Windows (Chocolatey)
choco install k6

2. 创建测试脚本 stress-test.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import http from 'k6/http';
import { check, sleep } from 'k6';

// 初始化配置
export let options = {
stages: [
{ duration: '30s', target: 50 }, // 30秒内逐步增加到50个虚拟用户
{ duration: '1m', target: 100 }, // 保持100用户1分钟
{ duration: '20s', target: 0 }, // 逐步降级到0
],
thresholds: {
http_req_duration: ['p(95)<500'], // 95%的请求必须低于500ms
http_req_failed: ['rate<0.01'], // 失败率低于1%
},
};

// 初始化函数(可选)
export function setup() {
console.log('Test setup: 初始化测试数据');
}

// 测试逻辑
export default function () {
const url = 'http://localhost:3000/api/users';

// 定义请求参数
const payload = JSON.stringify({
email: `testuser_${__VU}@example.com`,
password: 'test123',
});

const headers = { 'Content-Type': 'application/json' };

// 发送POST请求
const res = http.post(url, payload, { headers });

// 验证响应
check(res, {
'Status is 201': (r) => r.status === 201,
'Response has ID': (r) => JSON.parse(r.body).id !== undefined,
});

// 模拟用户等待时间(500ms-1.5s随机)
sleep(Math.random() * 1 + 0.5);
}

// 清理函数(可选)
export function teardown() {
console.log('Test teardown: 清理测试数据');
}

3. 启动你的Node.js服务

确保你的服务正在运行:

1
2
3
npm start
# 或
node server.js

4. 运行性能测试

1
k6 run stress-test.js

5. 结果分析示例

典型输出会包含以下关键指标:

1
2
3
4
5
6
7
8
9
10
11
scenarios: (79.77%) ✓ 3 scenarios, ✓ max 100 VUs, 02m30s max duration
data_received........: 12 MB 80 kB/s
data_sent............: 2.8 MB 19 kB/s
http_req_blocked.....: avg=1.2ms min=0s med=1µs max=120ms
http_req_connecting..: avg=1ms min=0s med=0s max=118ms
http_req_duration....: avg=250ms min=100ms med=220ms max=1.2s
http_req_failed......: 0.00% ✓ 0 ✗ 2345
http_req_receiving...: avg=1.2ms min=0s med=1ms max=25ms
http_req_sending.....: avg=0.5ms min=0s med=0s max=10ms
http_req_waiting.....: avg=248ms min=99ms med=218ms max=1.19s
vus..................: 100 min=100 max=100

6. 进阶配置建议

参数化测试数据

1
2
3
4
import { SharedArray } from 'k6';
const testData = new SharedArray('users', function () {
return JSON.parse(open('./test-data.json'));
});

多场景配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
export let options = {
scenarios: {
spike: {
executor: 'ramping-arrival-rate',
preAllocatedVUs: 100,
maxVUs: 500,
stages: [
{ target: 200, duration: '10s' }, // 快速增加到200 RPS
{ target: 200, duration: '1m' },
{ target: 0, duration: '10s' },
],
},
stress: {
executor: 'constant-vus',
vus: 300,
duration: '5m',
}
}
};

生成HTML报告

1
2
k6 run --out json=test_results.json stress-test.js
k6 convert test_results.json -O results.html

7. CI/CD 集成示例 (GitHub Actions)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
name: Performance Tests

on: [push]

jobs:
k6-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Start Node.js server
run: |
npm install
nohup node server.js > server.log 2>&1 &
- name: Install k6
run: sudo apt-get update && sudo apt-get install k6
- name: Run performance tests
run: k6 run --summary-export=results.json tests/stress-test.js
- name: Archive results
uses: actions/upload-artifact@v3
with:
name: performance-results
path: results.json

注意事项

  1. 根据实际API调整目标URL和请求参数
  2. 测试前确保数据库连接池配置足够
  3. 使用 k6 login cloud + k6 cloud script.js 可进行分布式云端测试
  4. 结合New Relic/Datadog等工具进行全链路监控

通过这个完整的示例,你可以系统性地验证Node.js应用的:

  • 并发处理能力
  • 内存泄漏风险
  • 数据库连接池效率
  • API响应稳定性
  • 错误处理机制健壮性