[ PROMPT_NODE_25258 ]
server-cache-lru
[ SKILL_DOCUMENTATION ]
## 跨请求 LRU 缓存
`React.cache()` 仅在单个请求内有效。对于跨顺序请求(用户先点击按钮 A 再点击按钮 B)共享的数据,请使用 LRU 缓存。
**实现:**
typescript
import { LRUCache } from 'lru-cache'
const cache = new LRUCache({
max: 1000,
ttl: 5 * 60 * 1000 // 5 分钟
})
export async function getUser(id: string) {
const cached = cache.get(id)
if (cached) return cached
const user = await db.user.findUnique({ where: { id } })
cache.set(id, user)
return user
}
// 请求 1: 数据库查询,结果被缓存
// 请求 2: 命中缓存,无数据库查询
当顺序用户操作在几秒钟内命中多个需要相同数据的端点时使用。
**配合 Vercel 的 [Fluid Compute](https://vercel.com/docs/fluid-compute) 使用:** LRU 缓存特别有效,因为多个并发请求可以共享同一个函数实例和缓存。这意味着缓存可以在请求之间持久存在,而无需像 Redis 这样的外部存储。
**在传统 Serverless 中:** 每个调用都在隔离环境中运行,因此请考虑使用 Redis 进行跨进程缓存。
参考:[https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)