缓存策略实现

实现数据缓存策略

提示词

请为以下场景实现缓存策略:

场景:[如热点数据查询/API响应/计算结果]
使用:[Redis/内存缓存/CDN]

要求:
1. 缓存键设计
2. 过期策略(TTL)
3. 缓存更新策略(Cache-Aside/Write-Through等)
4. 缓存穿透/击穿/雪崩防护
5. 缓存预热
6. 降级方案

给出代码实现。

示例输出

class CacheService {
  constructor(redis) {
    this.redis = redis;
    this.defaultTTL = 300; // 5分钟
  }

  // Cache-Aside模式
  async getOrSet(key, fetchFn, ttl = this.defaultTTL) {
    // 1. 查缓存
    const cached = await this.redis.get(key);
    if (cached) return JSON.parse(cached);

    // 2. 缓存未命中,查数据库(加锁防击穿)
    const lockAcquired = await this.redis.set(
      `lock:${key}`, '1', 'NX', 'EX', 10
    );
    if (!lockAcquired) {
      await new Promise(r => setTimeout(r, 100));
      return this.getOrSet(key, fetchFn, ttl);
    }

    try {
      const data = await fetchFn();
      // 空值也缓存(防穿透),但TTL短
      await this.redis.setex(key, data ? ttl : 60, JSON.stringify(data));
      return data;
    } finally {
      await this.redis.del(`lock:${key}`);
    }
  }

  // 主动失效
  async invalidate(pattern) {
    const keys = await this.redis.keys(pattern);
    if (keys.length) await this.redis.del(...keys);
  }
}
0

评论 0

更多

登录后可点赞、收藏、评论和举报。

还没有评论,先发起一个具体问题。