Node.js SSR 多级 LRU 缓存方案:租户隔离 + 自动过期 + 内存可控

发布时间:2026/7/12 4:37:07
Node.js SSR 多级 LRU 缓存方案:租户隔离 + 自动过期 + 内存可控 Node.js SSR 多级 LRU 缓存方案:租户隔离 + 自动过期 + 内存可控本文基于 SSR 服务端内存缓存实践整理,采用lru-cache实现两级缓存架构,适用于多租户/多站点 Node.js 服务场景。一、为什么需要两级缓存?在 SSR 渲染中,每次请求都要拉取语言包、站点配置、分类树等公共数据。如果每次都走 HTTP 请求:首屏 TTFB 被拖慢上游 API 压力增大多站点部署时,内存可能被无限撑大本方案采用两级 LRU 缓存:┌──────────────────────────────────────────────┐ │ NamespaceCacheHub(一级) │ │ 按 tenantId 隔离,最多 N 个租户,空闲自动淘汰 │ ├──────────────┬──────────────┬────────────────┤ │ ScopedLruStore│ScopedLruStore│ ScopedLruStore │ │ (site-a) │ (site-b) │ (site-c) │ ├──────────────┴──────────────┴────────────────┤ │ 每个租户内部:ScopedLruStore(二级) │ │ max=500, TTL=5min,缓存 languages/config 等 │ └──────────────────────────────────────────────┘层级类名职责一级NamespaceCacheHub管理多个租户缓存实例,限制租户数量二级ScopedLruStore单租户内的 key-value 缓存,带 TTL 和容量上限二、依赖安装npminstalllru-cachelru-cachev7+ 自带 TTL、dispose 回调、容量控制,比手写 Map + setTimeout 更可靠。三、核心实现3.1 默认配置constBASE_STORE_OPTIONS={max:500,// 单租户最多 500 条ttl:5*60*1000,// 默认 5 分钟过期updateAgeOnGet:false,// 读取不续期(固定 TTL)updateAgeOnHas:false,allowStale:false,// 不返回过期数据};3.2 一级:NamespaceCacheHubimport{LRUCache}from'lru-cache';exportclassNamespaceCacheHub{constructor(options={}){this.registry=newLRUCache({max:options.maxTenants||50,// 最多 50 个租户ttl:options.tenantIdleTTL||30*60*1000,// 30 分钟未访问淘汰租户dispose:(store,tenantId)={console.log(`[CacheHub] 淘汰租户缓存:${tenantId}`);store?.flush?.();},});this.sweepTimer=setInterval(()=this.sweep(),60*1000);}register(tenantId,store){this.registry.set(tenantId,store);}resolve(tenantId){returnthis.registry.get(tenantId);}drop(tenantId){conststore=this.registry.get(tenantId);if(store){store.flush();this.registry.delete(tenantId);}}flushAll(){this.registry.