k6
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesek6
k6
k6 is a developer-centric, open-source load testing tool suitable for testing APIs, microservices, and websites. It is written in Go but you script tests in JavaScript.
k6是一款以开发者为中心的开源负载测试工具,适用于测试API、微服务和网站。它由Go语言编写,但你可以使用JavaScript编写测试脚本。
When to Use
适用场景
- API Load Testing: The gold standard for modern API performance testing.
- CI/CD Integration: Very lightweight binary (or Docker), easy to gate capabilities ("fail if p95 > 500ms").
- Developer Friendly: Uses JS (ES6) for scripting, so backend/frontend devs can write tests.
- API负载测试:现代API性能测试的黄金标准。
- CI/CD集成:体积极轻的二进制文件(或Docker镜像),轻松设置准入条件(如“若p95延迟超过500ms则测试失败”)。
- 开发者友好:使用JS(ES6)编写脚本,后端/前端开发者均可编写测试用例。
Quick Start
快速开始
javascript
import http from "k6/http";
import { sleep, check } from "k6";
export const options = {
vus: 10,
duration: "30s",
};
export default function () {
const res = http.get("http://test.k6.io");
check(res, {
"status was 200": (r) => r.status == 200,
});
sleep(1);
}Run with .
k6 run script.jsjavascript
import http from "k6/http";
import { sleep, check } from "k6";
export const options = {
vus: 10,
duration: "30s",
};
export default function () {
const res = http.get("http://test.k6.io");
check(res, {
"status was 200": (r) => r.status == 200,
});
sleep(1);
}运行命令:。
k6 run script.jsCore Concepts
核心概念
Virtual Users (VUs)
虚拟用户(VUs)
Simulated users that run your script in a loop. They are concurrent but not browser-based (unless you use xk6-browser), so they are CPU efficient.
模拟用户循环运行你的测试脚本。它们是并发的,但并非基于浏览器(除非使用xk6-browser),因此CPU效率极高。
Checks & Thresholds
检查与阈值
- Check: Boolean assertion (like an assert). Doesn't fail the test, just reports pass/fail % at end.
- Threshold: Pass/Fail criteria for the CI pipeline.
javascript
export const options = {
thresholds: {
http_req_duration: ["p(95)<500"], // 95% of requests must complete below 500ms
},
};- 检查(Check):布尔断言(类似断言语句)。不会导致测试失败,仅在测试结束时报告通过率/失败率。
- 阈值(Threshold):用于CI流水线的通过/失败判定标准。
javascript
export const options = {
thresholds: {
http_req_duration: ["p(95)<500"], // 95%的请求必须在500ms内完成
},
};Best Practices (2025)
2025年最佳实践
Do:
- Modularize: Split logic into folders. k6 supports ES modules ().
import { ... } from './utils.js' - Use Scenarios: Mix different patterns (ramping up, constant arrival rate) in one test.
- Correlate specific data: Ensure you are not just hitting cache. Use dynamic data (random IDs).
Don't:
- Don't treat it like a browser: Standard k6 does not parse HTML or execute JS on the page. It just hits endpoints. Use
httpmodule if you strictly need browser rendering (but it's heavier).k6-browser
建议做法:
- 模块化:将逻辑拆分为多个文件夹。k6支持ES模块()。
import { ... } from './utils.js' - 使用场景(Scenarios):在单个测试中混合不同模式(如逐步加压、恒定到达率)。
- 关联特定数据:确保测试并非仅命中缓存。使用动态数据(如随机ID)。
避免做法:
- 不要将其当作浏览器使用:标准k6的模块不会解析HTML或执行页面中的JS,仅会请求端点。如果确实需要浏览器渲染,请使用
http模块(但资源消耗更高)。k6-browser