在CentOS环境下,针对Node.js应用的性能测试可分为基准测试(评估吞吐量、响应时间)、负载测试(模拟高并发场景)、内存分析(检测泄漏)三大类,常用工具如下:
ab -c 50 -t 15 http://127.0.0.1:3000/(-c表示并发数,-t表示测试时长)。sudo yum install -y wrk;wrk -t12 -c400 -d30s http://127.0.0.1:3000/(-t线程数,-c并发连接数,-d测试时长)。sudo npm install -g artillery;test.yaml):config:
target: "http://localhost:3000"
phases:
- duration: 60 # 持续60秒
arrivalRate: 20 # 每秒20个请求
scenarios:
- flow:
- get: /
- post:
url: "/api/data"
json: { key: "value" }
运行命令:artillery run test.yaml。sudo npm install -g heapdump;require('heapdump').writeSnapshot('/tmp/heap.snapshot')(触发后会生成.heapsnapshot文件,可用Chrome DevTools分析)。sudo npm install -g v8-profiler-node8;const profile = require('v8-profiler-node8').takeSnapshot(); profile.export().pipe(fs.createWriteStream('cpu.prof'))。const { performance } = require('perf_hooks');
const start = performance.now();
// 待测试代码(如循环、数据库查询)
const end = performance.now();
console.log(`耗时:${end - start}ms`);
console.time('test');
// 待测试代码
console.timeEnd('test'); // 输出:test: Xms
top(实时进程资源占用)、htop(增强版top)、vmstat(虚拟内存统计)、iostat(磁盘IO)等工具监控服务器状态,及时发现资源瓶颈。--inspect启动Node.js应用(node --inspect app.js),通过Chrome DevTools进行可视化性能分析(如CPU火焰图、内存快照);或使用--prof生成性能日志(node --prof app.js),再用node --prof-process解析。worker_threads模块拆分任务到多个线程;fs.promises.readFile替代fs.readFile);通过上述方法,可全面评估CentOS上Node.js应用的性能,定位并解决瓶颈问题,确保应用在高负载下的稳定性。