import http from 'k6/http'; import { check, sleep } from 'k6'; import { Rate, Trend } from 'k6/metrics'; const errorRate = new Rate('errors'); const responseTime = new Trend('response_time'); export const options = { stages: [ { duration: '1m', target: 50 }, // 1分钟内增加到50用户 { duration: '2m', target: 100 }, // 2分钟内增加到100用户 { duration: '3m', target: 200 }, // 3分钟内增加到200用户 { duration: '5m', target: 300 }, // 5分钟内增加到300用户(压力峰值) { duration: '2m', target: 100 }, // 2分钟内减少到100用户 { duration: '1m', target: 0 }, // 1分钟内减少到0 ], thresholds: { http_req_duration: ['p(95)<1000', 'p(99)<2000'], // 95%请求<1s, 99%请求<2s http_req_failed: ['rate<0.05'], // 错误率<5%(压力测试允许更高) errors: ['rate<0.05'], }, }; const BASE_URL = __ENV.BASE_URL || 'http://localhost:3000'; export default function () { const scenarios = [ { method: 'GET', path: '/', name: '首页' }, { method: 'GET', path: '/api/health', name: '健康检查' }, { method: 'POST', path: '/api/contact', name: '联系表单', body: JSON.stringify({ name: 'Test User', email: 'test@example.com', phone: '13800138000', message: 'This is a test message', }) }, ]; const scenario = scenarios[Math.floor(Math.random() * scenarios.length)]; let res; if (scenario.method === 'POST') { res = http.post(`${BASE_URL}${scenario.path}`, scenario.body, { headers: { 'Content-Type': 'application/json' }, tags: { name: scenario.name }, }); } else { res = http.get(`${BASE_URL}${scenario.path}`, { tags: { name: scenario.name }, }); } const success = check(res, { 'status is 200 or 201': (r) => [200, 201].includes(r.status), 'response time < 1000ms': (r) => r.timings.duration < 1000, }); errorRate.add(!success); responseTime.add(res.timings.duration); sleep(Math.random() * 2 + 0.5); // 0.5-2.5秒随机等待 } export function handleSummary(data) { return { 'performance/stress-test-summary.json': JSON.stringify(data, null, 2), }; }