用 JavaScript 写 HTTP 压测,希望在 CI 里以退出码判断性能门禁是否通过。k6 适合 API、网关和微服务的基准测试、容量验证与回归对比;浏览器渲染、复杂交互和录制回放不是它的强项,需要浏览器级指标时应另选工具。
default 函数。10 VU × 30 秒 不等于固定请求数,取决于每次迭代耗时和 sleep。constant-vus、ramping-vus、constant-arrival-rate、ramping-arrival-rate。p(95)<500、rate<0.01;失败时 k6 以退出码 99 结束。http_reqs、http_req_duration、http_req_failed、iterations、vus、checks 等,可加 tag 后分组设阈值。安装与运行:
brew install k6
docker run --rm -i grafana/k6 run - <script.js
最小脚本 script.js:
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
vus: 10,
duration: '30s',
};
export default function () {
const res = http.get(`${__ENV.BASE_URL}/health`);
check(res, { 'status is 200': (r) => r.status === 200 });
sleep(1);
}
用 arrival-rate 场景施加固定速率,并配置阈值:
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
scenarios: {
load: {
executor: 'ramping-arrival-rate',
startRate: 10,
preAllocatedVUs: 20,
maxVUs: 100,
stages: [
{ target: 50, duration: '2m' },
{ target: 50, duration: '5m' },
{ target: 0, duration: '30s' },
],
},
},
thresholds: {
'http_req_duration': ['p(95)<800'],
'http_req_failed': ['rate<0.01'],
'checks': ['rate>0.99'],
},
};
export default function () {
const res = http.post(
`${__ENV.BASE_URL}/api/orders`,
JSON.stringify({ sku: 'A-1', qty: 1 }),
{ headers: { 'Content-Type': 'application/json' } },
);
check(res, { 'created 201': (r) => r.status === 201 });
sleep(1 + Math.random());
}
命令行执行并导出结果:
k6 run -e BASE_URL=https://staging.example.com script.js
k6 run -e BASE_URL=https://staging.example.com \
--out json=results.json --summary-export=summary.json script.js
GitHub Actions 中运行:
- uses: actions/checkout@v4
- uses: grafana/setup-k6-action@v1
- uses: grafana/run-k6-action@v1
with:
path: tests/load/*.js
flags: -e BASE_URL=${{ vars.STAGING_URL }}
常用指标如下:
| 指标 | 含义 | 重点 |
|---|---|---|
http_reqs |
请求总数与每秒速率 | 吞吐是否随压力线性增长 |
http_req_duration |
请求总耗时 | p(95)、p(99) 比平均值更能暴露长尾 |
http_req_failed |
失败请求比例 | 默认把非 2xx/3xx 和网络错误算失败 |
checks |
断言通过率 | 不配 threshold 时不会让测试失败 |
RPS 上不去但延迟也不高时,先看压测机 CPU、网络出口和目标端连接数,不要直接得出“服务能扛住”的结论。
sleep(1) 会显著压低 RPS;如果目标是固定 QPS,用 arrival-rate executor,而不是堆 VU。thresholds 引用 checks,否则 CI 仍然成功。http_req_failed 误报。localhost 不是宿主机;macOS/Windows 用 host.docker.internal,Linux 加 --add-host。checks 和 thresholds 是什么关系,为什么 check 失败但 CI 仍然通过?
小程序版
微信扫码,随时查命令