如何封装一个带缓存的 HttpClient,支持 TTL 与内存/LocalStorage 双存储?

解读

国内中高级 Angular 面试常把“自己写缓存”作为手写代码题出现,考察点集中在:

  1. 对 Angular DI 与拦截器机制的熟练度;
  2. 对 RxJS 流式缓存(shareReplay、takeUntil、timer)的掌控;
  3. 对浏览器存储上限、同步阻塞、序列化成本的工程判断;
  4. 对内存+本地双存储一致性、降级策略、TTL 淘汰逻辑的落地能力。

题目看似简单,但想拿到“A+评级”必须给出生产级方案:线程安全、内存泄漏防护、容错回退、Tree-shakable、单元测试友好,并能一句话讲清“为何不用现成的 @ngneat/cashew”。

知识点

  • HttpInterceptor 接口与 multi 注入
  • RxJS 冷流与热流:shareReplay、timer、takeUntil、finalize
  • TypeScript 泛型约束与 keyof
  • localStorage 同步异常、QuotaExceededError 降级
  • TTL 时间轮与惰性淘汰(lazy expiration)
  • 内存泄漏:拦截器长期持有闭包、定时器未清理
  • Angular 服务生命周期:providedIn: 'root' 单例与 OnDestroy
  • 测试策略:HttpClientTestingController + fakeAsync + tick

答案

  1. 模型层
export interface CacheEntry<T> {
  data: T;
  expireAt: number; // ms
}
export type CacheStore = 'memory' | 'localStorage';
  1. 缓存仓库(双存储 + TTL 惰性淘汰)
@Injectable({ providedIn: 'root' })
export class CacheRepository {
  private memory = new Map<string, CacheEntry<any>>();
  private readonly LS_KEY = 'ng_cache';

  get<T>(key: string): T | null {
    const hit = this.memory.get(key) ?? this.lsGet<T>(key);
    if (!hit) return null;
    if (Date.now() > hit.expireAt) {
      this.delete(key);
      return null;
    }
    return hit.data;
  }

  set<T>(key: string, data: T, ttl: number, store: CacheStore): void {
    const entry: CacheEntry<T> = { data, expireAt: Date.now() + ttl };
    if (store === 'memory') this.memory.set(key, entry);
    else this.lsSet(key, entry);
  }

  delete(key: string): void {
    this.memory.delete(key);
    try {
      const all = JSON.parse(localStorage.getItem(this.LS_KEY) || '{}');
      delete all[key];
      localStorage.setItem(this.LS_KEY, JSON.stringify(all));
    } catch {}
  }

  private lsGet<T>(key: string): CacheEntry<T> | null {
    try {
      const all = JSON.parse(localStorage.getItem(this.LS_KEY) || '{}');
      return all[key] || null;
    } catch {
      return null;
    }
  }

  private lsSet<T>(key: string, entry: CacheEntry<T>): void {
    try {
      const all = JSON.parse(localStorage.getItem(this.LS_KEY) || '{}');
      all[key] = entry;
      localStorage.setItem(this.LS_KEY, JSON.stringify(all));
    } catch (e) {
      // QuotaExceededError 降级为仅内存
    }
  }
}
  1. 缓存拦截器(核心)
@Injectable()
export class CacheInterceptor implements HttpInterceptor {
  constructor(private cache: CacheRepository) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (req.method !== 'GET') return next.handle(req);

    const ttl = Number(req.headers.get('x-cache-ttl') || 60000);
    const store = (req.headers.get('x-cache-store') as CacheStore) || 'memory';
    const key = `ng:${req.urlWithParams}`;

    const cached = this.cache.get<any>(key);
    if (cached !== null) return of(new HttpResponse({ body: cached, status: 200 }));

    return next.handle(req).pipe(
      filter(event => event instanceof HttpResponse),
      tap(event => this.cache.set(key, (event as HttpResponse<any>).body, ttl, store)),
      shareReplay({ bufferSize: 1, refCount: true })
    );
  }
}
  1. 模块级注入
@NgModule({
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: CacheInterceptor, multi: true }
  ]
})
export class CoreModule {}
  1. 使用姿势
this.http.get<User[]>('/api/users', {
  headers: new HttpHeaders({
    'x-cache-ttl': '300000',      // 5 分钟
    'x-cache-store': 'localStorage'
  })
});
  1. 单元测试(节选)
it('应命中缓存且只发一次真实请求', fakeAsync(() => {
  service.getUsers().subscribe();
  tick();
  httpMock.expectOne('/api/users').flush(mockUsers);

  service.getUsers().subscribe(); // 第二次
  tick();
  httpMock.verify(); // 无新请求
}));

拓展思考

  1. 内存上限如何量化?可引入 LRU 策略,限制 Map 最大 200 条,超出后自动淘汰最久未使用。
  2. localStorage 跨标签页同步需监听 window 'storage' 事件,及时清理其他标签已失效的缓存,防止“脏读”。
  3. SSR 场景下 localStorage 不存在,需在工厂函数中注入 PLATFORM_ID 做浏览器侧降级,防止 Node 端报错。
  4. POST/PUT/DELETE 可变操作成功后,可维护一份基于 URL 模式的“失效白名单”,自动批量删除相关 GET 缓存,实现写后读一致性。
  5. 若接口返回 ETag,可升级为HTTP 304 协商缓存,把 TTL 逻辑与浏览器原生缓存链结合起来,减少带宽。
  6. 对大体积列表接口可切片缓存(pagination key),避免整表失效;或引入 IndexedDB 做二级存储,突破 5 MB 限制。
  7. 最后,回答面试官“为何不自研而用 @ngneat/cashew”时,一句话:“cashew 默认内存存储、无 localStorage 降级、无 TTL 惰性淘汰,不能满足我们 PWA 离线首屏<300 ms 的 SLA。”