DataLoader批处理与多级缓存策略
在DataLoader之上实现基于TTL和LRU的多级缓存,减少数据库压力并保证数据新鲜度。 · 难度:入门 · +10XP
DataLoader批处理与多级缓存策略
标准DataLoader只提供单次请求内的缓存,本课程扩展它支持跨请求缓存。你将学习实现一个CachedLoader,内部使用node-cache或Redis作为L1缓存,DataLoader自带的Map作为L2缓存。同时设计缓存失效策略:基于最大年龄(TTL)和最近最少使用(LRU)。通过自定义cacheKeyFn支持复合主键。最后讲解如何在Resolver层手动清除特定缓存条目,以及调试缓存命中率。
class CachedLoader {
constructor(batchFn, options) {
this.loader = new DataLoader(batchFn);
this.cache = new LRUCache({ max: 500, ttl: 60000 });
}
async load(key) {
const cached = this.cache.get(key);
if (cached) return cached;
const result = await this.loader.load(key);
this.cache.set(key, result);
return result;
}
}