Spaces:
Sleeping
Sleeping
| /** | |
| * 稳健版高并发压力测试脚本 | |
| * 采用异步并发池模式,模拟真实高并发场景 | |
| */ | |
| const TARGET_URL = 'http://127.0.0.1:7865/api/concurrency/vote'; | |
| const TOTAL_REQUESTS = 2000; | |
| const CONCURRENCY = 100; | |
| async function runTest() { | |
| console.log(`\n🔥 [压力测试启动]`); | |
| console.log(`----------------------------------------`); | |
| console.log(`🎯 目标接口: ${TARGET_URL}`); | |
| console.log(`📦 总请求数: ${TOTAL_REQUESTS}`); | |
| console.log(`⚡️ 并发强度: ${CONCURRENCY}`); | |
| console.log(`----------------------------------------\n`); | |
| const startTime = Date.now(); | |
| let completed = 0; | |
| let successCount = 0; | |
| let failCount = 0; | |
| const durations = []; | |
| // 任务队列 | |
| const tasks = Array.from({ length: TOTAL_REQUESTS }, (_, i) => i); | |
| // 工作函数:不断从队列中取任务执行 | |
| async function worker() { | |
| while (tasks.length > 0) { | |
| const id = tasks.shift(); | |
| const reqStart = Date.now(); | |
| try { | |
| const res = await fetch(TARGET_URL, { | |
| method: 'POST', | |
| headers: { 'Content-Type': 'application/json' }, | |
| body: JSON.stringify({ | |
| candidateId: `candidate-${Math.floor(Math.random() * 5)}`, | |
| userId: `user-${id}-${Math.random().toString(36).slice(2)}` | |
| }) | |
| }); | |
| const duration = Date.now() - reqStart; | |
| durations.push(duration); | |
| if (res.ok) { | |
| successCount++; | |
| } else { | |
| failCount++; | |
| } | |
| } catch (err) { | |
| failCount++; | |
| } finally { | |
| completed++; | |
| // 每完成 10% 打印一次进度 | |
| if (completed % (TOTAL_REQUESTS / 10) === 0 || completed === TOTAL_REQUESTS) { | |
| const progress = ((completed / TOTAL_REQUESTS) * 100).toFixed(0); | |
| console.log(`📈 进度: ${progress}% (${completed}/${TOTAL_REQUESTS}) - 成功: ${successCount}, 失败: ${failCount}`); | |
| } | |
| } | |
| } | |
| } | |
| // 启动指定数量的 worker | |
| const workers = Array.from({ length: CONCURRENCY }, worker); | |
| await Promise.all(workers); | |
| const endTime = Date.now(); | |
| const totalTime = (endTime - startTime) / 1000; | |
| const qps = (TOTAL_REQUESTS / totalTime).toFixed(2); | |
| // 统计分析 | |
| durations.sort((a, b) => a - b); | |
| const avgTime = (durations.reduce((a, b) => a + b, 0) / durations.length || 0).toFixed(2); | |
| const p95 = durations[Math.floor(durations.length * 0.95)] || 0; | |
| console.log(`\n📊 [测试报告]`); | |
| console.log(`========================================`); | |
| console.log(`⏱️ 总耗时 : ${totalTime.toFixed(3)} 秒`); | |
| console.log(`🚀 QPS (吞吐量) : ${qps} req/sec`); | |
| console.log(`✅ 成功请求 : ${successCount}`); | |
| console.log(`❌ 失败请求 : ${failCount}`); | |
| console.log(`----------------------------------------`); | |
| console.log(`延迟统计 (毫秒):`); | |
| console.log(` - 平均 (Avg) : ${avgTime} ms`); | |
| console.log(` - P95 (95%) : ${p95} ms`); | |
| console.log(`========================================\n`); | |
| } | |
| runTest().catch(console.error); | |