项目文件夹

文件
2026-07-13 21:36:17 +08:00

42 行
1.3 KiB
Markdown

此文件含有模棱两可的 Unicode 字符
此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。
---
title: 跨请求 LRU 缓存
impact: HIGH
impactDescription: 跨请求缓存
tags: server, cache, lru, cross-request
---
## 跨请求 LRU 缓存
`React.cache()` 仅在单个请求内有效。对于跨顺序请求(用户先点击按钮 A,再点击按钮 B)共享的数据,请使用 LRU 缓存。
**实现方式:**
```typescript
import { LRUCache } from 'lru-cache'
const cache = new LRUCache<string, any>({
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