选择合适的Node.js版本
确保使用最新的稳定版或LTS(长期支持)版本,新版本通常包含性能改进、bug 修复和安全更新,能有效提升应用稳定性和执行效率。
优化系统内核参数
调整CentOS内核参数以提升网络连接和内存管理性能。编辑/etc/sysctl.conf文件,添加或修改以下关键参数:
net.ipv4.tcp_tw_reuse = 1:启用TCP连接复用,减少TIME_WAIT状态连接占用;net.ipv4.tcp_max_syn_backlog = 8192:增加半连接队列长度,应对高并发连接请求;net.core.somaxconn = 4096:提升本地端口范围和最大连接队列长度;fs.file-max = 65536:增加系统最大文件描述符限制。sudo sysctl -p使配置生效。使用反向代理服务器(如Nginx)
通过Nginx作为反向代理,可实现以下优化:
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://localhost:3000; # 转发到Node.js应用
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
location ~* \.(jpg|css|js)$ {
expires 30d; # 静态资源缓存30天
access_log off;
}
}
利用Cluster模块实现多进程
Node.js内置的cluster模块可创建多个工作进程(Worker),共享服务器端口并并行处理请求。示例代码:
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
for (let i = 0; i < numCPUs; i++) {
cluster.fork(); // 创建与CPU核心数相同的Worker
}
cluster.on('exit', (worker) => {
console.log(`Worker ${worker.process.pid} died, restarting...`);
cluster.fork(); // Worker崩溃时自动重启
});
} else {
http.createServer((req, res) => {
res.writeHead(200);
res.end('Hello from Worker ' + process.pid);
}).listen(3000);
console.log(`Worker ${process.pid} started`);
}
这种方式能充分利用多核CPU,显著提升并发处理能力。
优化内存管理与避免泄漏
--max-old-space-size参数增加Node.js进程的内存上限(如4GB),避免内存溢出。可通过PM2配置(ecosystem.config.js)或环境变量设置:module.exports = {
apps: [{
name: 'my-app',
script: 'app.js',
instances: 'max',
exec_mode: 'cluster',
max_memory_restart: '4G' // 内存超过4GB时自动重启
}]
};
removeListener)、避免全局变量滥用(如global.xxx)、使用heapdump或memwatch-next工具检测内存泄漏。使用缓存减少重复计算
node-cache或Redis缓存频繁访问的数据(如数据库查询结果、API响应),减少重复计算和数据库访问次数。示例node-cache用法:const NodeCache = require('node-cache');
const cache = new NodeCache({ stdTTL: 60 }); // 缓存60秒
app.get('/data', (req, res) => {
const cachedData = cache.get('myData');
if (cachedData) return res.json(cachedData);
const data = fetchDataFromDB(); // 模拟数据库查询
cache.set('myData', data);
res.json(data);
});
异步编程与非阻塞I/O
app.get('/async-data', async (req, res) => {
try {
const data = await fetchDataFromDB(); // 异步获取数据
res.json(data);
} catch (err) {
res.status(500).send('Error: ' + err.message);
}
});
fs.readFileSync、child_process.spawnSync等同步API,防止阻塞事件循环。使用PM2进行进程管理
PM2是Node.js的生产级进程管理器,提供以下优化功能:
sudo npm install pm2 -g
pm2 start app.js --name "my-app" --instances max # 启动应用并使用所有CPU核心
pm2 monit # 监控应用状态
优化数据库访问
mysql2(MySQL)、pg-pool(PostgreSQL)等库的连接池功能,减少频繁建立和断开数据库连接的开销。示例mysql2连接池:const mysql = require('mysql2/promise');
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'password',
database: 'mydb',
waitForConnections: true,
connectionLimit: 10, // 连接池大小
queueLimit: 0
});
app.get('/db-data', async (req, res) => {
const [rows] = await pool.query('SELECT * FROM users'); // 使用连接池查询
res.json(rows);
});
SELECT *(只查询所需字段),使用EXPLAIN分析查询性能。监控与性能分析
process.memoryUsage()查看内存使用情况,node --prof生成CPU分析报告(通过chrome://tracing查看)。New Relic、Datadog或Easy-Monitor进行实时性能监控,快速定位瓶颈(如慢查询、高CPU占用)。