mcpField
P
performance-optimization

performance-optimization

github.com/pluginagentmarketplace开发264 次安装43 周前更新
代码仓库

关于 performance-optimization

面向优化 Node.js 后端性能的开发者技能,涵盖缓存、集群、性能分析、数据库与响应优化及监控,并提供代码示例和生产环境检查清单。

主要功能

  1. 01使用 Redis 和内存缓存
  2. 02通过集群利用 CPU 核心
  3. 03分析 CPU 与内存性能
  4. 04优化数据库查询和连接池
  5. 05压缩响应并分页
  6. 06监控性能并执行负载测试

适用场景

  1. 01诊断后端请求缓慢问题
  2. 02为 Node.js 服务准备生产部署
  3. 03缓解数据库查询瓶颈
  4. 04评估服务在流量下的表现

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/pluginagentmarketplace/custom-plugin-nodejs --skill performance-optimization

安装后在 Claude Code 中输入/performance-optimization确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

assets/
config.yaml
references/
GUIDE.md
scripts/
helper.py

详细介绍

性能优化技能

掌握 Node.js 性能优化,构建快速、可扩展且高效的后端应用。

快速开始

从 4 个方面进行优化:

  1. 缓存 - Redis/内存缓存
  2. 集群 - 使用所有 CPU 核心
  3. 性能分析 - 查找瓶颈
  4. 监控 - 跟踪性能

核心概念

使用 Redis 缓存
const redis = require('redis');
const client = redis.createClient({ url: process.env.REDIS_URL });

// Cache middleware
async function cacheMiddleware(req, res, next) {
  const key = `cache:${req.originalUrl}`;

  const cached = await client.get(key);
  if (cached) {
    return res.json(JSON.parse(cached));
  }

  // Override res.json to cache response
  const originalJson = res.json.bind(res);
  res.json = (data) => {
    client.setEx(key, 3600, JSON.stringify(data)); // 1 hour
    originalJson(data);
  };

  next();
}

// Usage
app.get('/api/users', cacheMiddleware, getUsers);
集群(使用所有 CPU 核心)
const cluster = require('cluster');
const os = require('os');

if (cluster.isMaster) {
  const numCPUs = os.cpus().length;

  console.log(`Master ${process.pid} starting ${numCPUs} workers`);

  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', (worker) => {
    console.log(`Worker ${worker.process.pid} died, restarting...`);
    cluster.fork();
  });
} else {
  // Worker process - start Express server
  const app = require('./app');
  app.listen(3000, () => {
    console.log(`Worker ${process.pid} started`);
  });
}

学习路径

初学者(2-3 周)
  • ✅ 实现基础缓存
  • ✅ 使用压缩中间件
  • ✅ 优化数据库查询
  • ✅ 启用生产模式
中级(4-5 周)
  • ✅ 配置 Redis 缓存
  • ✅ 实现集群
  • ✅ 数据库索引
  • ✅ 响应分页
高级(6-8 周)
  • ✅ CPU/内存性能分析
  • ✅ 负载均衡
  • ✅ CDN 集成
  • ✅ 性能监控

数据库优化

连接池
// PostgreSQL pool
const { Pool } = require('pg');

const pool = new Pool({
  max: 20,  // Max connections
  min: 5,   // Min connections
  idleTimeoutMillis: 30000
});

// MongoDB with Mongoose
mongoose.connect(uri, {
  maxPoolSize: 10,
  minPoolSize: 5
});
查询优化
// ❌ Bad: N+1 query problem
const users = await User.find();
for (const user of users) {
  user.posts = await Post.find({ userId: user.id }); // N queries
}

// ✅ Good: Single query with join
const users = await User.find().populate('posts'); // 1 query

// Add indexes
userSchema.index({ email: 1 }, { unique: true });
userSchema.index({ createdAt: -1 });

// Use lean() for read-only queries (faster)
const users = await User.find().lean(); // Returns plain objects
分页
async function getUsers(req, res) {
  const page = parseInt(req.query.page) || 1;
  const limit = parseInt(req.query.limit) || 10;
  const skip = (page - 1) * limit;

  const [users, total] = await Promise.all([
    User.find().limit(limit).skip(skip),
    User.countDocuments()
  ]);

  res.json({
    data: users,
    pagination: {
      page,
      limit,
      total,
      pages: Math.ceil(total / limit)
    }
  });
}

响应优化

压缩
const compression = require('compression');

app.use(compression({
  level: 6,
  threshold: 1024  // Only compress > 1KB
}));
响应缓存标头
app.get('/api/static-data', (req, res) => {
  res.set('Cache-Control', 'public, max-age=3600'); // Cache 1 hour
  res.json(data);
});

// For frequently changing data
res.set('Cache-Control', 'public, max-age=60'); // Cache 1 minute

异步优化

并行执行
// ❌ Sequential (300ms)
const users = await getUsers();    // 100ms
const posts = await getPosts();    // 100ms
const comments = await getComments(); // 100ms

// ✅ Parallel (100ms)
const [users, posts, comments] = await Promise.all([
  getUsers(),
  getPosts(),
  getComments()
]);
流式处理大型文件
const fs = require('fs');

// ❌ Bad: Load entire file into memory
app.get('/large-file', async (req, res) => {
  const data = await fs.promises.readFile('large.txt');
  res.send(data);
});

// ✅ Good: Stream file
app.get('/large-file', (req, res) => {
  const stream = fs.createReadStream('large.txt');
  stream.pipe(res);
});

CPU 性能分析

内置性能分析器
# Start with profiler
node --prof app.js

# Generate readable output
node --prof-process isolate-0x*.log > profile.txt
性能测量
const { performance } = require('perf_hooks');

const start = performance.now();
await heavyOperation();
const end = performance.now();
console.log(`Operation took ${end - start}ms`);

内存优化

避免内存泄漏
// ❌ Bad: Memory leak
const cache = {};
app.get('/data/:id', (req, res) => {
  cache[req.params.id] = data; // Never cleaned up
  res.json(data);
});

// ✅ Good: Use LRU cache with limits
const LRU = require('lru-cache');
const cache = new LRU({
  max: 500,  // Max 500 items
  maxAge: 1000 * 60 * 60  // TTL: 1 hour
});
监控内存
const used = process.memoryUsage();
console.log({
  rss: `${Math.round(used.rss / 1024 / 1024)}MB`,
  heapTotal: `${Math.round(used.heapTotal / 1024 / 1024)}MB`,
  heapUsed: `${Math.round(used.heapUsed / 1024 / 1024)}MB`
});

监控与 APM

Winston 日志记录
const winston = require('winston');

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

// Request logging
app.use((req, res, next) => {
  const start = Date.now();

  res.on('finish', () => {
    logger.info('HTTP Request', {
      method: req.method,
      url: req.url,
      status: res.statusCode,
      duration: Date.now() - start
    });
  });

  next();
});
APM 工具
  • New Relic - 全栈监控
  • Datadog - 基础设施 + APM
  • Dynatrace - AI 驱动的监控
  • PM2 Plus - 专为 Node.js 打造的监控

负载测试

Artillery
# load-test.yml
config:
  target: 'http://localhost:3000'
  phases:
    - duration: 60
      arrivalRate: 10

scenarios:
  - name: "Get users"
    flow:
      - get:
          url: "/api/users"
artillery run load-test.yml

性能检查清单

  • ✅ 启用 Node.js 生产模式(NODE_ENV=production)
  • ✅ 使用集群(PM2 或 cluster module)
  • ✅ 实现缓存(Redis)
  • ✅ 使用数据库连接池
  • ✅ 添加数据库索引
  • ✅ 压缩响应(gzip)
  • ✅ 使用 CDN 提供静态资源
  • ✅ 优化图像
  • ✅ 对大型数据集进行分页
  • ✅ 流式处理大型文件
  • ✅ 使用 APM 工具进行监控

生产环境优化

// production.js
if (process.env.NODE_ENV === 'production') {
  // Trust proxy (for load balancer)
  app.set('trust proxy', 1);

  // Disable x-powered-by header
  app.disable('x-powered-by');

  // Enable compression
  app.use(compression());

  // Use production logger
  app.use(productionLogger());
}

适用场景

在以下情况下优化性能:

  • 应用运行缓慢或无响应
  • 需要处理高流量
  • 数据库查询成为瓶颈
  • 内存使用量过高
  • 需要横向扩展
  • 准备部署到生产环境

相关技能

  • Express REST API(优化 API 性能)
  • Async Programming(异步优化)
  • Database Integration(查询优化)
  • Docker Deployment(生产环境部署)

资源

评论

支持 Markdown