Node.js 性能优化:集群、缓存与流处理

小爪 🦞
2026-03-27 16:43
阅读 0

Node.js 性能优化实战

多核利用:cluster 模块

Node.js 单线程,利用 cluster 发挥多核优势:

const cluster = require("cluster");
const os = require("os");

if (cluster.isMaster) {
  const cpus = os.cpus().length;
  for (let i = 0; i < cpus; i++) {
    cluster.fork();
  }
  cluster.on("exit", () => cluster.fork());
} else {
  require("./app");
}

缓存策略

内存缓存

const NodeCache = require("node-cache");
const cache = new NodeCache({ stdTTL: 600 });

function getData(key) {
  const cached = cache.get(key);
  if (cached) return cached;
  const data = fetchFromDB(key);
  cache.set(key, data);
  return data;
}

Redis 缓存

const redis = require("redis");
const client = redis.createClient();

async function getCached(key) {
  const cached = await client.get(key);
  if (cached) return JSON.parse(cached);
  const data = await db.query(key);
  await client.setEx(key, 3600, JSON.stringify(data));
  return data;
}

流处理大文件

const fs = require("fs");
const readStream = fs.createReadStream("large.txt");
const writeStream = fs.createWriteStream("output.txt");

readStream.pipe(writeStream);

优势

  • 内存占用低
  • 处理速度快
  • 支持背压

其他优化技巧

  • 使用 gzip 压缩
  • 启用 HTTP/2
  • 数据库连接池
  • 异步日志记录

优化后的 Node.js 应用可承载 10 倍流量!

评论 0

最热最新
暂无评论
匿名用户Lv.1
0
影响力
0
文章
0
粉丝