// Node.js 并发负载测试(替代 k6) const BASE = 'http://172.31.12.249:18080/api/hss'; const H = { 'Content-Type': 'application/json', 'X-Tenant-Id': '1', 'X-Org-Id': '1', 'X-User-Role': 'ADMIN' }; let total = 0, passed = 0, failed = 0; const start = Date.now(); const startMem = process.memoryUsage().heapUsed; async function req(path, method = 'GET', body = null) { const headers = { ...H, 'Idempotency-Key': 'load-' + Math.random().toString(36).slice(2,10) }; const r = await fetch(BASE + path, { method, headers, body: body ? JSON.stringify(body) : undefined }); return r.status; } // 阶段1: 阶梯负载 (5 → 20 → 0 并发) const stages = [ { duration: 5000, concurrency: 5 }, { duration: 10000, concurrency: 10 }, { duration: 15000, concurrency: 20 }, { duration: 10000, concurrency: 10 }, { duration: 5000, concurrency: 5 }, ]; async function runStage(concurrency, durationMs) { const endTime = Date.now() + durationMs; const tasks = []; while (Date.now() < endTime) { for (let i = 0; i < concurrency; i++) { tasks.push((async () => { total++; try { const paths = ['/admin/dashboard', '/analytics/summary', '/master/service-items', '/applications?page=1&size=10', '/admin/work-orders?page=1&size=10']; const status = await req(paths[Math.floor(Math.random() * paths.length)]); if (status === 200) passed++; else failed++; } catch (e) { failed++; } })()); } if (tasks.length > 500) { await Promise.all(tasks.splice(0, 200)); } await new Promise(r => setTimeout(r, 1000 / concurrency)); } await Promise.all(tasks); const elapsed = ((Date.now() - start) / 1000).toFixed(1); console.log(` [${elapsed}s] concurrency=${concurrency} passed=${passed} failed=${failed} total=${total}`); } async function main() { console.log('=== 负载测试:阶梯并发 5→10→20→10→5 ===\n'); for (const s of stages) { await runStage(s.concurrency, s.duration); } const elapsed = ((Date.now() - start) / 1000).toFixed(1); const rps = (total / elapsed).toFixed(1); const passRate = total > 0 ? (passed / total * 100).toFixed(1) : '0'; const memUsed = ((process.memoryUsage().heapUsed - startMem) / 1024 / 1024).toFixed(1); console.log(`\n=== 结果 ===`); console.log(`总请求: ${total} 通过: ${passed} 失败: ${failed} 通过率: ${passRate}%`); console.log(`耗时: ${elapsed}s RPS: ${rps} 内存: ${memUsed}MB`); } main().catch(console.error);