[ PROMPT_NODE_27986 ]
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:命中缓存,无数据库查询
当连续的用户操作在几秒钟内访问多个需要相同数据的端点时使用此方法。在 Serverless 环境中,考虑使用 Redis 进行跨进程缓存。
参考:[https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)