系统级配置是Node.js网络性能的基础,主要涉及文件描述符限制和内核参数调优:
ulimit -n 65535
命令;永久生效需编辑/etc/security/limits.conf
,添加* soft nofile 65535
和* hard nofile 65535
(允许所有用户最多打开65535个文件)。/etc/sysctl.conf
,添加/修改以下参数以提升TCP连接效率和复用率:
net.core.somaxconn = 65535
:增大TCP监听队列长度,避免连接被拒绝;net.ipv4.tcp_max_syn_backlog = 65535
:增大SYN队列长度,应对高并发连接请求;net.ipv4.ip_local_port_range = 1024 65535
:扩大可用端口范围,减少端口耗尽问题;net.ipv4.tcp_tw_reuse = 1
:允许复用TIME_WAIT状态的连接,降低新建连接开销;net.ipv4.tcp_fin_timeout = 30
:缩短TIME_WAIT状态等待时间(默认60秒),加快连接回收;net.core.rmem_max = 16777216
/net.core.wmem_max = 16777216
:增大TCP读写缓冲区大小,提升数据传输效率。sysctl -p
使配置生效。应用层优化聚焦于协议选择、并发处理和资源管理:
http2
模块创建安全服务器示例:const http2 = require('http2');
const fs = require('fs');
const server = http2.createSecureServer({
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.crt')
});
server.on('stream', (stream, headers) => {
stream.respond({ ':status': 200, 'content-type': 'text/html' });
stream.end('<h1>Hello World</h1>');
});
server.listen(8443);
cluster
模块利用多核CPU,创建多个工作进程共享端口,提升并发处理能力。示例:const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
for (let i = 0; i < numCPUs; i++) cluster.fork();
cluster.on('exit', (worker) => console.log(`Worker ${worker.process.pid} died`));
} else {
http.createServer((req, res) => res.end('Hello from worker')).listen(8000);
}
async/await
或Promise
;处理大文件或数据时,使用Stream
(如fs.createReadStream()
)逐块读取/写入,减少内存占用。emitter.removeListener()
),避免内存泄漏;使用node-cache
或lru-cache
缓存频繁访问的数据,减少重复计算或网络请求。/etc/sysctl.conf
,添加net.ipv4.tcp_fastopen = 3
,允许客户端在握手阶段发送数据,减少往返延迟,执行sysctl -p
生效。server {
listen 80;
server_name example.com;
location /static/ {
root /path/to/static/files; # 缓存静态文件
}
location / {
proxy_pass http://localhost:3000; # 转发动态请求到Node.js
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
compression
中间件(Express/Koa)启用Gzip/Brotli压缩,减少传输数据量。示例:const compression = require('compression');
const express = require('express');
const app = express();
app.use(compression()); // 自动压缩响应
app.get('/', (req, res) => res.send('Compressed response'));
app.listen(3000);
Chrome DevTools
(通过--inspect
启动Node.js)分析事件循环、内存使用;借助Prometheus
+Grafana
搭建实时监控面板,跟踪请求延迟、吞吐量等指标。ELK Stack
(Elasticsearch+Logstash+Kibana)收集和分析网络日志,识别慢请求、连接错误等问题根源。以上策略需根据实际业务场景(如并发量、数据类型)调整,例如高并发API服务可优先优化集群和HTTP/2,静态资源较多的应用则应加强反向代理和压缩。