CentOS上Node.js性能優化策略
確保CentOS系統及內核為最新版本,通過sudo yum update -y更新系統包,修復已知漏洞并提升底層性能。同時,升級GCC編譯器以支持更高版本的Node.js編譯需求。
修改/etc/sysctl.conf文件優化網絡與內存管理,提升并發處理能力:
# 增加文件描述符限制(支持更多并發連接)
echo "fs.file-max = 65536" >> /etc/sysctl.conf
# 啟用TCP快速復用(減少TIME_WAIT狀態連接)
echo "net.ipv4.tcp_tw_reuse = 1" >> /etc/sysctl.conf
# 增加TCP同步隊列長度(應對高并發連接)
echo "net.core.somaxconn = 4096" >> /etc/sysctl.conf
# 調整網絡緩沖區大?。ㄌ嵘龜祿鬏斝剩?/span>
echo "net.core.netdev_max_backlog = 2000" >> /etc/sysctl.conf
# 應用參數變更
sudo sysctl -p
同時,調整/etc/security/limits.conf增加用戶進程與文件打開限制:
* soft nofile 65536
* hard nofile 65536
若使用firewalld,允許應用端口(如80、443、3000)通過,并關閉不必要的端口:
sudo firewall-cmd --permanent --add-port=80/tcp
sudo firewall-cmd --permanent --add-port=443/tcp
sudo firewall-cmd --reload
如需更高性能,可臨時關閉firewalld(生產環境需謹慎):
sudo systemctl stop firewalld
sudo systemctl disable firewalld
通過NodeSource倉庫安裝長期支持(LTS)版本,確保穩定性與性能優化:
curl -sL https://rpm.nodesource.com/setup_18.x | sudo bash -
sudo yum install -y nodejs
node -v # 驗證版本
通過NODE_OPTIONS環境變量增加Node.js進程的內存上限(默認1.5GB),避免內存溢出:
export NODE_OPTIONS="--max_old_space_size=4096" # 設置為4GB
可將此命令添加到~/.bashrc或/etc/profile中永久生效。
使用PM2進程管理器實現進程守護、負載均衡與日志管理:
sudo npm install pm2 -g
pm2 start app.js --name "my-app" --instances max # 根據CPU核心數啟動多個實例
pm2 save # 保存進程列表
pm2 startup # 設置開機自啟
使用async/await或Promise替代回調函數,避免阻塞事件循環。例如:
// 回調方式(易阻塞)
fs.readFile('file.txt', (err, data) => {
if (err) throw err;
console.log(data);
});
// async/await方式(非阻塞)
async function readFile() {
try {
const data = await fs.promises.readFile('file.txt', 'utf-8');
console.log(data);
} catch (err) {
console.error(err);
}
}
readFile();
處理大文件(如上傳、下載)時使用流(Stream),減少內存占用:
const fs = require('fs');
const readStream = fs.createReadStream('large-file.zip');
const writeStream = fs.createWriteStream('output.zip');
readStream.pipe(writeStream); // 流式傳輸
id、username)創建索引,加速查詢。mysql2或pg的連接池功能,避免頻繁建立/斷開數據庫連接:const mysql = require('mysql2/promise');
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'password',
database: 'test',
waitForConnections: true,
connectionLimit: 10, // 連接池大小
queueLimit: 0
});
node-cache庫緩存頻繁訪問的數據(如配置項、熱點數據):const NodeCache = require('node-cache');
const cache = new NodeCache({ stdTTL: 60 }); // 緩存60秒
const data = cache.get('key');
if (!data) {
const newData = fetchDataFromDB();
cache.set('key', newData);
res.send(newData);
} else {
res.send(data);
}
使用Nginx作為反向代理,處理靜態文件、負載均衡與SSL卸載:
server {
listen 80;
server_name example.com;
# 靜態文件緩存(減少Node.js請求)
location ~* \.(jpg|jpeg|png|gif|css|js)$ {
root /var/www/html;
expires 30d; # 緩存30天
access_log off;
}
# 動態請求轉發至Node.js(負載均衡)
location / {
proxy_pass http://nodejs_upstream;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
# 定義Node.js上游服務器(多實例負載均衡)
upstream nodejs_upstream {
server 127.0.0.1:3000;
server 127.0.0.1:3001;
server 127.0.0.1:3002;
}
使用performance模塊監控代碼執行時間:
const { performance, PerformanceObserver } = require('perf_hooks');
const obs = new PerformanceObserver((items) => {
console.log(items.getEntries()[0].duration); // 輸出執行時間
performance.clearMarks();
});
obs.observe({ entryTypes: ['measure'] });
performance.mark('start');
// 需要監控的代碼
performance.mark('end');
performance.measure('My Operation', 'start', 'end');
pm2 monit查看CPU、內存使用情況,或使用pm2 plus(付費)進行實時監控。使用winston或pino記錄應用日志,結合ELK Stack(Elasticsearch+Logstash+Kibana)分析日志,定位性能問題:
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
logger.info('Application started');
使用heapdump模塊生成堆快照,分析內存泄漏源:
npm install heapdump --save
在代碼中添加堆快照生成邏輯:
const heapdump = require('heapdump');
// 在可疑位置生成堆快照(如內存增長時)
heapdump.writeSnapshot('/tmp/snapshot_' + Date.now() + '.heapsnapshot');
打開Chrome瀏覽器,訪問chrome://inspect,點擊“Open dedicated DevTools for Node”,選擇“Memory” tab,加載堆快照,通過“Comparison”功能對比不同時間點的堆內存,找出持續增長的對象(如未釋放的全局變量、事件監聽器)。
let/const替代var,避免意外掛載到global對象。destroy或close方法中移除事件監聽器:const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const emitter = new MyEmitter();
emitter.on('event', () => console.log('Event triggered'));
// 不再需要時移除
emitter.off('event');
通過以上策略,可全面提升CentOS上Node.js應用的性能、穩定性與可維護性。