{T}

高性能架构 学习笔记(第 6 部分)

7.2 核心优化策略

7.2.1 缓存优化

javascript
// 多级缓存策略
const cacheStrategy = {
  // L1: 本地缓存(内存)
  localCache: {
    tool: 'node-cache',
    ttl: 60,
    maxSize: '100MB',
    useCase: '热点数据、配置信息'
  },
  
  // L2: 分布式缓存
  distributedCache: {
    tool: 'Redis',
    ttl: 3600,
    useCase: '会话存储、共享数据'
  },
  
  // L3: CDN 缓存
  cdn: {
    provider: 'CloudFlare / 阿里云 CDN',
    ttl: 86400,
    useCase: '静态资源、API 响应'
  }
}

// 缓存实现示例
class CacheManager {
  constructor() {
    this.localCache = new Map()
    this.redis = new Redis()
  }
  
  async get(key) {
    // 1. 先查本地缓存
    if (this.localCache.has(key)) {
      return this.localCache.get(key)
    }
    
    // 2. 再查 Redis
    const value = await this.redis.get(key)
    if (value) {
      // 回填本地缓存
      this.localCache.set(key, value)
      return value
    }
    
    // 3. 查数据库
    const data = await this.queryDB(key)
    if (data) {
      // 写入缓存
      await this.redis.set(key, data, 'EX', 3600)
      this.localCache.set(key, data)
    }
    
    return data
  }
}

7.2.2 异步处理

javascript
// 异步处理提升性能
const asyncOptimization = {
  // 场景:订单创建
  
  //  同步处理(慢)
  sync: async (orderData) => {
    // 1. 创建订单
    const order = await Order.create(orderData)
    
    // 2. 扣减库存
    await Inventory.decrease(order.productId)
    
    // 3. 扣除余额
    await Account.deduct(order.userId, order.amount)
    
    // 4. 发送通知邮件
    await Email.send(order.userId, '订单创建成功')
    
    // 5. 发送短信通知
    await SMS.send(order.userId, '订单创建成功')
    
    return order
    // 总耗时:所有操作耗时之和
  },
  
  //  异步处理(快)
  async: async (orderData) => {
    // 1. 创建订单
    const order = await Order.create(orderData)
    
    // 2. 异步处理其他任务
    Promise.all([
      Inventory.decrease(order.productId),
      Account.deduct(order.userId, order.amount)
    ])
    
    // 3. 发送到消息队列,异步处理
    MessageQueue.publish('order.created', {
      orderId: order.id,
      userId: order.userId
    })
    
    return order
    // 总耗时:仅核心操作耗时
  }
}

// 消息队列消费者
MessageQueue.subscribe('order.created', async (message) => {
  const { orderId, userId } = message
  
  // 异步发送通知
  await Email.send(userId, '订单创建成功')
  await SMS.send(userId, '订单创建成功')
})

7.2.3 数据库优化

sql
-- 数据库优化示例

--  慢查询(全表扫描)
SELECT * FROM orders WHERE user_id = 12345;

--  添加索引
CREATE INDEX idx_user_id ON orders(user_id);

--  查询优化(只查询需要的字段)
SELECT id, status, amount FROM orders 
WHERE user_id = 12345 
ORDER BY created_at DESC 
LIMIT 20;

--  分页优化(避免 OFFSET 过大)
-- 方式1:使用游标
SELECT id, status, amount FROM orders 
WHERE user_id = 12345 AND id > 100000
ORDER BY id ASC
LIMIT 20;

-- 方式2:延迟关联
SELECT o.* FROM orders o
INNER JOIN (
  SELECT id FROM orders
  WHERE user_id = 12345
  ORDER BY created_at DESC
  LIMIT 10000, 20
) AS tmp ON o.id = tmp.id;

八、高性能架构设计模式