Ubuntu Nodejs性能怎样优化

优化Ubuntu上的Node.js性能可以通过多个方面来实现,包括系统配置、Node.js应用本身的优化以及使用一些工具来监控和调优。以下是一些常见的优化策略:

系统配置优化

  • 增加文件描述符限制

    ulimit -n 65535
    

    将这个命令添加到 /etc/security/limits.conf 文件中,以便永久生效。

  • 调整内核参数
    编辑 /etc/sysctl.conf 文件,添加或修改以下参数:

    net.core.somaxconn = 4096
    net.ipv4.tcp_max_syn_backlog = 4096
    net.ipv4.ip_local_port_range = 1024 65535
    net.ipv4.tcp_tw_reuse = 1
    net.ipv4.tcp_fin_timeout = 30
    

    然后运行 sudo sysctl -p 使更改生效。

  • 使用SSD:如果可能的话,使用SSD硬盘可以显著提高I/O性能。

Node.js应用优化

  • 使用最新版本的Node.js
    使用 nvm(Node Version Manager)来管理和切换Node.js版本。

    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
    source ~/.bashrc
    nvm install node
    nvm use node
    
  • 代码优化

    • 避免不必要的全局变量。
    • 使用异步操作来避免阻塞事件循环。
    • 减少CPU密集型任务的执行时间。
    • 使用缓存来减少重复计算。
  • 使用Cluster模块

    const cluster = require('cluster');
    const http = require('http');
    const numCPUs = require('os').cpus().length;
    if (cluster.isMaster) {
      console.log(`Master ${process.pid} is running`);
      // Fork workers.
      for (let i = 0; i < numCPUs class="hljs-title function_">fork();
      }
      cluster.on('exit', (worker, code, signal) => {
        console.log(`worker ${worker.process.pid} died`);
      });
    } else {
      // Workers can share any TCP connection
      // In this case it is an HTTP server
      http.createServer((req, res) => {
        res.writeHead(200);
        res.end('hello world
    

');
}).listen(8000);
console.log(Worker ${process.pid} started);
}


- **使用PM2**:
PM2是一个进程管理器,可以帮助你管理和监控Node.js应用。
```bash
npm install pm2 -g
pm2 start app.js -i max

监控和调优

  • 使用Node.js内置的性能钩子

    const { performance, PerformanceObserver } = require('perf_hooks');
    const obs = new PerformanceObserver((list) => {
      console.log(list.getEntries()[0].duration);
      observer.disconnect();
    });
    obs.observe({ entryTypes: ['measure'] });
    performance.mark('A');
    // Some code here...
    performance.mark('B');
    performance.measure('A to B', 'A', 'B');
    
  • 使用第三方监控工具

    • New Relic
    • Datadog
    • Prometheus + Grafana

通过这些优化策略,你可以显著提高Node.js在Ubuntu上的性能。记住,优化是一个持续的过程,需要根据应用的具体情况进行调整。