CentOS系统级网络配置优化
/etc/security/limits.conf,添加* soft nofile 65535和* hard nofile 65535;临时生效可使用ulimit -n 65535命令。/etc/sysctl.conf,添加/修改以下参数提升TCP性能:net.core.somaxconn = 65535(最大连接队列长度)、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超时时间,单位秒);执行sysctl -p使配置生效。Node.js应用层网络配置优化
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 World')).listen(8000);
}
Stream(如fs.createReadStream()、res.write())替代内存缓冲,减少内存占用。反向代理与负载均衡配置
server {
listen 80;
server_name example.com;
location /static/ {
root /path/to/static/files; # 缓存静态文件
expires 30d;
}
location / {
proxy_pass http://localhost:3000; # 转发动态请求
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
upstream模块将请求分发至多个Node.js实例,支持Round Robin(默认)、Least Connections(最少连接)等策略,提升吞吐量。配置示例:upstream node_servers {
server localhost:3000;
server localhost:3001;
server localhost:3002;
}
server {
listen 80;
location / {
proxy_pass http://node_servers;
}
}
location /ws {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
性能监控与持续优化
--inspect参数启动Node.js应用,使用Chrome DevTools的Performance面板分析事件循环、CPU占用、内存使用情况,找出性能瓶颈(如同步代码、内存泄漏)。