阅读量:38
在CentOS上优化Node.js代码可以从多个方面入手,包括系统配置、Node.js应用配置、代码优化等。以下是一些具体的步骤和建议:
1. 系统配置优化
1.1 增加文件描述符限制
Node.js应用通常需要处理大量的并发连接,因此需要增加系统的文件描述符限制。
# 查看当前限制
ulimit -n
# 临时增加限制
ulimit -n 65535
# 永久增加限制
echo "* soft nofile 65535" >> /etc/security/limits.conf
echo "* hard nofile 65535" >> /etc/security/limits.conf
1.2 调整内核参数
编辑 /etc/sysctl.conf 文件,增加以下参数:
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.ip_local_port_range = 1024 65535
然后应用更改:
sysctl -p
2. Node.js应用配置优化
2.1 使用PM2管理Node.js应用
PM2是一个进程管理工具,可以帮助你管理和监控Node.js应用。
# 安装PM2
npm install pm2 -g
# 启动应用
pm2 start app.js --name my-app
# 查看应用状态
pm2 status
# 监控应用
pm2 monit
2.2 配置HTTP/2
如果你的Node.js应用使用Express框架,可以启用HTTP/2来提高性能。
const express = require('express');
const http2 = require('http2');
const fs = require('fs');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World!');
});
const server = http2.createSecureServer({
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.crt')
}, app);
server.listen(3000, () => {
console.log('Server is running on https://localhost:3000');
});
3. 代码优化
3.1 使用异步操作
尽可能使用异步操作来避免阻塞事件循环。
// 同步操作
const fs = require('fs');
const data = fs.readFileSync('file.txt', 'utf8');
// 异步操作
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
3.2 减少内存使用
避免不必要的内存分配,使用流式处理大数据。
const fs = require('fs');
const readStream = fs.createReadStream('large-file.txt');
readStream.on('data', (chunk) => {
console.log(chunk.toString());
});
3.3 使用缓存
对于频繁访问的数据,可以使用缓存来减少数据库查询次数。
const NodeCache = require('node-cache');
const cache = new NodeCache();
cache.set('key', 'value', 60); // 缓存60秒
const value = cache.get('key');
console.log(value);
4. 监控和日志
4.1 使用监控工具
使用Prometheus和Grafana来监控Node.js应用的性能。
# 安装Prometheus
wget https://github.com/prometheus/prometheus/releases/download/v2.30.3/prometheus-2.30.3.linux-amd64.tar.gz
tar xvfz prometheus-2.30.3.linux-amd64.tar.gz
cd prometheus-2.30.3.linux-amd64
./prometheus --config.file=prometheus.yml
4.2 日志管理
使用Winston或Pino来记录日志,并配置日志轮转。
const winston = require('winston');
const { createLogger, format, transports } = winston;
const logger = createLogger({
level: 'info',
format: format.combine(
format.timestamp(),
format.json()
),
transports: [
new transports.File({ filename: 'error.log', level: 'error' }),
new transports.File({ filename: 'combined.log' })
]
});
logger.info('Hello world!');
通过以上步骤,你可以在CentOS上优化Node.js代码,提高应用的性能和稳定性。