温馨提示×

CentOS Node.js网络如何优化

小樊
50
2025-10-04 22:18:28
栏目: 编程语言

CentOS系统级网络配置优化

  • 调整文件描述符限制:Node.js处理高并发需大量文件描述符,需修改/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应用层网络配置优化

  • 启用HTTP/2协议:HTTP/2的多路复用、头部压缩特性可减少延迟,提升传输效率。示例代码:
    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())替代内存缓冲,减少内存占用。

反向代理与负载均衡配置

  • 使用Nginx作为反向代理:Nginx可处理静态文件、缓存请求、缓解DoS攻击,并将动态请求转发至Node.js,提升整体性能。配置示例:
    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;
      }
    }
    
  • 实现负载均衡:通过Nginx的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;
      }
    }
    
  • 代理WebSocket连接:Nginx可优化WebSocket连接的稳定性,配置示例:
    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占用、内存使用情况,找出性能瓶颈(如同步代码、内存泄漏)。
  • 第三方监控工具:引入Prometheus(收集指标)+ Grafana(可视化)监控应用的QPS、响应时间、错误率;使用ELK Stack(Elasticsearch+Logstash+Kibana)集中管理日志,快速定位异常。

0