CentOS上Node.js內存管理優化策略
let
/const
替代var
),并在不再需要時將其設置為null
(如global.someData = null
)。emitter.removeListener('event', handler)
移除不再需要的監聽器,用clearInterval(timer)
/clearTimeout(timer)
清除定時器。fs.readFileSync
),改用fs.createReadStream()
逐塊讀取,fs.createWriteStream()
逐塊寫入,顯著降低內存占用。Map
/Set
替代傳統對象/數組(避免原型鏈查找開銷),用ArrayBuffer
處理二進制數據。--max-old-space-size
參數調整老生代內存上限(單位:MB/GB),例如:node --max-old-space-size=4096 your_script.js # 設置為4GB
若使用PM2,可在ecosystem.config.js
中配置:module.exports = {
apps: [{
name: 'your-app',
script: 'your_script.js',
max_memory_restart: '4G' // 內存超過4GB時自動重啟
}]
};
/etc/sysctl.conf
優化內存管理,減少Swap依賴:vm.swappiness=10 # 降低Swap使用傾向(0~100,值越小越傾向于使用物理內存)
vm.vfs_cache_pressure=50 # 控制內核回收用于目錄和inode緩存的內存的傾向(值越大回收越積極)
應用更改:sysctl -p
。ulimit -n 65535
永久生效需修改/etc/security/limits.conf
,添加:* soft nofile 65535
* hard nofile 65535
```。
process.memoryUsage()
方法獲取進程內存使用情況(單位:字節),包括:
rss
(Resident Set Size):進程占用的物理內存;heapTotal
/heapUsed
:堆內存的總分配量與已使用量;external
:V8管理的C++對象內存(如Buffer)。setInterval(() => {
const mem = process.memoryUsage();
console.log(`RSS: ${(mem.rss / 1024 / 1024).toFixed(2)}MB, Heap Used: ${(mem.heapUsed / 1024 / 1024).toFixed(2)}MB`);
}, 5000);
```。
npm install heapdump
,代碼中調用:const heapdump = require('heapdump');
heapdump.writeSnapshot('/tmp/heapdump.heapsnapshot'); // 觸發快照生成
node --inspect your_script.js
啟動調試模式,訪問chrome://inspect
,選擇進程并進入“Memory”面板,進行堆快照、內存分配時間線分析。npm install memwatch-next
,代碼中監聽leak
事件:const memwatch = require('memwatch-next');
memwatch.on('leak', (info) => {
console.error('Memory leak detected:', info); // 輸出泄漏信息(如增長的對象數量)
});
```。
node-cache
或Redis
緩存,但設置合理的過期時間(如ttl
)或大小限制(如最大緩存條目數),避免緩存無限增長。cluster
模式啟動多進程(exec_mode: 'cluster'
),或使用child_process
創建子進程處理CPU密集型任務(避免阻塞事件循環)。