使用 k6 為 API 進行壓力測試

安裝套件

安裝套件。

1
brew install k6

建立專案

建立專案。

1
2
mkdir stress-testing
cd stress-testing

建立 main.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
import http from 'k6/http';
import { check, sleep } from 'k6';

export default function () {
const url = 'http://test.k6.io';
const payload = JSON.stringify({
foo: 'bar',
});

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

const res = http.get(url, payload, params);
check(res, { 'status was 200': (r) => r.status == 200 });
sleep(1);

// console.log({
// status: res.status,
// });
}

export const options = {
vus: 50,
duration: '10s',
};

執行測試。

1
k6 run main.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
          /\      |‾‾| /‾‾/   /‾‾/   
/\ / \ | |/ / / /
/ \/ \ | ( / ‾‾\
/ \ | |\ \ | (‾) |
/ __________ \ |__| \__\ \_____/ .io

execution: local
script: main.js
output: -

scenarios: (100.00%) 1 scenario, 50 max VUs, 40s max duration (incl. graceful stop):
* default: 50 looping VUs for 10s (gracefulStop: 30s)


✓ status was 200

checks.........................: 100.00% ✓ 191 ✗ 0
data_received..................: 2.5 MB 225 kB/s
data_sent......................: 56 kB 4.9 kB/s
http_req_blocked...............: avg=412.54ms min=1µs med=7µs max=3.21s p(90)=2.35s p(95)=2.37s
http_req_connecting............: avg=214.3ms min=0s med=0s max=1.01s p(90)=1.01s p(95)=1.01s
http_req_duration..............: avg=508.98ms min=223.47ms med=298.19ms max=3.65s p(90)=790.28ms p(95)=807.22ms
{ expected_response:true }...: avg=508.98ms min=223.47ms med=298.19ms max=3.65s p(90)=790.28ms p(95)=807.22ms
http_req_failed................: 0.00% ✓ 0 ✗ 382
http_req_receiving.............: avg=873.08µs min=12µs med=78µs max=237.5ms p(90)=219.6µs p(95)=1.47ms
http_req_sending...............: avg=159.16µs min=5µs med=23µs max=3.09ms p(90)=283.89µs p(95)=1.41ms
http_req_tls_handshaking.......: avg=190.41ms min=0s med=0s max=2.19s p(90)=1.34s p(95)=1.36s
http_req_waiting...............: avg=507.95ms min=223.33ms med=297.66ms max=3.64s p(90)=789.38ms p(95)=803.82ms
http_reqs......................: 382 33.888138/s
iteration_duration.............: avg=2.84s min=1.48s med=2.02s max=7.95s p(90)=4.93s p(95)=6.15s
iterations.....................: 191 16.944069/s
vus............................: 16 min=16 max=50
vus_max........................: 50 min=50 max=50


running (11.3s), 00/50 VUs, 191 complete and 0 interrupted iterations
default ✓ [======================================] 50 VUs 10s

參考資料