use cache: remote
了解如何使用 "use cache: remote" 指令,借助远程缓存 handler 实现持久化的共享缓存。
虽然 use cache 指令足以满足大多数应用需求,但你可能会发现缓存操作的重新运行频率高于预期,或者你的上游服务(CMS、数据库、外部 API)受到的访问次数超出预期。这可能是因为 use cache 将条目存储在内存中,而这有固有的局限性:
- 缓存条目被逐出,为新条目腾出空间
- 部署环境中的内存限制
- 缓存无法在请求之间或服务器重启后持久化
请注意,use cache 在服务端缓存之外仍然有价值:它会告知 Next.js 哪些内容可以预取,并为客户端导航定义过期时间。
'use cache: remote' 指令使你可以声明式地指定某个缓存输出应存储在远程缓存而非内存中,从而提供在所有服务器实例之间共享的持久化缓存。这需要权衡:基础设施成本以及缓存查找期间的网络延迟。
用法#
要使用 'use cache: remote',请在 next.config.ts 文件中启用 cacheComponents 标志:
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
}
export default nextConfig/** @type {import('next').NextConfig} */
const nextConfig = {
cacheComponents: true,
}
module.exports = nextConfig然后,在你确定适合远程缓存的函数或组件中添加 'use cache: remote'。handler 的实现通过 cacheHandlers 配置,不过托管服务商通常会自动提供该配置。如果你自行托管,请参阅 cacheHandlers 配置参考来设置缓存存储。
何时避免远程缓存#
- 如果你已经有一个包裹数据层的服务端键值存储,
use cache可能就足以将数据纳入静态外壳,而无需增加另一层缓存 - 如果由于邻近性或本地访问,操作已经很快(< 50ms),那么远程缓存查找可能不会提升性能
- 如果每个请求的缓存 key 大多具有唯一值(搜索过滤器、价格范围、用户特定参数),缓存利用率将接近于零
- 如果数据频繁变化(几秒到几分钟),缓存命中会很快过期,导致频繁未命中并等待上游重新验证
何时适合远程缓存#
当内容被推迟到请求时(静态外壳之外)时,远程缓存的价值最大。这通常发生在组件访问请求值(如 cookies()、headers() 或 searchParams)时,这会将其置于 Suspense 边界内。在这种情况下:
- 每个请求都会执行该组件并查找缓存
- 在无服务器环境中,每个实例都有自己的临时内存,缓存命中率较低
- 远程缓存提供跨所有实例的共享缓存,提高命中率并降低后端负载
'use cache: remote' 的典型适用场景:
- 受速率限制的 API:你的上游服务有速率限制或请求配额,你可能会触及这些限制
- 保护缓慢的后端:你的数据库或 API 在高流量下成为瓶颈
- 开销大的操作:重复运行成本高的数据库查询或计算
- 不稳定或不可靠的服务:偶尔失败或存在可用性问题的外部服务
在这些情况下,远程缓存的成本和延迟是值得的,因为可以避免更糟糕的结果(速率限制错误、后端过载、高昂的计算账单或用户体验下降)。
对于静态外壳内容,use cache 通常就足够了。如果你的上游源无法处理并发的重新验证请求(例如受速率限制的 CMS),use cache: remote 可充当共享缓存层。这与在数据库前放置键值存储的模式相同,只是通过代码声明。
use cache: remote 与 use cache 和 use cache: private 的区别#
Next.js 提供三种缓存指令,各自针对不同的使用场景:
| 特性 | use cache | 'use cache: remote' | 'use cache: private' |
|---|---|---|---|
| 服务端缓存 | 内存或缓存 handler | 远程缓存 handler | 无 |
| 缓存范围 | 所有用户共享 | 所有用户共享 | 每个客户端(浏览器) |
| 能否直接访问 cookies/headers | 否(必须作为参数传入) | 否(必须作为参数传入) | 是 |
| 服务端缓存利用率 | 静态外壳之外可能较低 | 高(跨实例共享) | 不适用 |
| 额外成本 | 无 | 基础设施(存储、网络) | 无 |
| 延迟影响 | 无 | 缓存 handler 查找 | 无 |
| 跨部署持久化 | 否 | 否 | 不适用 |
跨部署的持久化#
远程缓存条目不会跨部署持久化。缓存 key 包含 deploymentId(如果已配置)或 buildId,因此新的构建会生成新的 key,之前构建的条目将无法再访问。有关完整的 key 组成,请参阅缓存 key。
这是有意设计的。在两次构建之间,函数的标识哈希或其返回值的结构可能会发生变化。升级 CMS 客户端、重构缓存函数或更改依赖项都可能产生与旧调用方预期不符的值,因此跨部署复用条目存在提供过期或格式错误数据的风险。
如果你需要跨部署持久化的条目,请对非 fetch 函数使用 unstable_cache,或依赖 fetch 缓存。
使用运行时数据缓存#
use cache 和 'use cache: remote' 都不能直接访问 cookies 或搜索参数等运行时值。你可以提取这些值,并将它们作为参数传给缓存函数。有关此模式,请参阅使用运行时数据。
小知识:
use cache将条目存储在内存中。在无服务器环境中,内存不在实例之间共享,且通常在响应请求后即被销毁,导致运行时缓存频繁未命中。
缓存 key 的注意事项#
请谨慎选择要包含在缓存 key 中的值。每个唯一值都会创建一个单独的缓存条目,从而降低缓存利用率。请看这个带搜索过滤器的示例:
import { Suspense } from 'react'
export default async function ProductsPage({
params,
searchParams,
}: {
params: Promise<{ category: string }>
searchParams: Promise<{ minPrice?: string }>
}) {
return (
<Suspense fallback={<div>Loading...</div>}>
<ProductList params={params} searchParams={searchParams} />
</Suspense>
)
}
async function ProductList({
params,
searchParams,
}: {
params: Promise<{ category: string }>
searchParams: Promise<{ minPrice?: string }>
}) {
const { category } = await params
const { minPrice } = await searchParams
// 仅按 category 缓存(唯一值较少)
// 不包含价格过滤器(唯一值很多)
const products = await getProductsByCategory(category)
// 在内存中过滤价格,而不是创建缓存条目
// 为每个价格值创建条目
const filtered = minPrice
? products.filter((p) => p.price >= parseFloat(minPrice))
: products
return <div></div>
}
async function getProductsByCategory(category: string) {
'use cache: remote'
// 只有 category 属于缓存 key 的一部分
// 比缓存每个价格过滤器值的利用率高得多
return db.products.findByCategory(category)
}在此示例中,远程 handler 为每个缓存条目存储更多数据(某个类别中的所有产品),以实现更高的缓存命中率。当缓存未命中的成本(命中你的后端)超过较大条目的存储成本时,这样做是值得的。
同样的原则也适用于用户特定数据。与其直接按用户缓存数据,不如使用用户偏好来确定要缓存的共享数据。
例如,如果用户在会话中具有语言偏好,请提取该偏好并用它来缓存共享内容:
- 不要对
getUserProfile(sessionID)进行远程缓存(这会为每个用户创建一个条目) - 而是对
getCMSContent(language)进行远程缓存,为每种语言创建一个条目
import { cookies } from 'next/headers'
import { cacheLife } from 'next/cache'
export async function WelcomeMessage() {
// 提取语言偏好(并非每个用户唯一)
const language = (await cookies()).get('language')?.value || 'en'
// 基于语言缓存(唯一值较少:en、es、fr、de 等)
// 所有偏好 'en' 的用户共享同一个缓存条目
const content = await getCMSContent(language)
return <div>{content.welcomeMessage}</div>
}
async function getCMSContent(language: string) {
'use cache: remote'
cacheLife({ expire: 3600 })
// 创建约 10-50 个缓存条目(每种语言一个)
// 而不是数千个(每个用户一个)
return cms.getHomeContent(language)
}这样,所有偏好相同语言的用户共享一个缓存条目,从而提高缓存利用率并降低 CMS 的负载。
两个示例中的模式相同:找到唯一值较少的维度(类别与价格、语言与用户 ID),基于该维度缓存,并在内存中过滤或选择其余部分。
如果 getUserProfile 使用的服务无法随前端负载扩展,你仍可以使用 use cache 指令并配合较短的 cacheLife 进行内存缓存。不过,对于大多数用户数据,你可能希望直接从数据源获取(如上文所述,数据源可能已被包裹在键值存储中)。
只有在你有合规要求,或无法重构为将运行时数据作为参数传入时,才使用 'use cache: private'。
嵌套规则#
远程缓存有特定的嵌套规则:
- 远程缓存可以嵌套在其他远程缓存中(
'use cache: remote') - 远程缓存可以嵌套在普通缓存中(
'use cache') - 远程缓存不能嵌套在私有缓存中(
'use cache: private') - 私有缓存不能嵌套在远程缓存中
// 有效:远程缓存嵌套在远程缓存中
async function outerRemote() {
'use cache: remote'
const result = await innerRemote()
return result
}
async function innerRemote() {
'use cache: remote'
return getData()
}
// 有效:远程缓存嵌套在普通缓存中
async function outerCache() {
'use cache'
// 当推迟到请求时,内部的远程缓存将生效
const result = await innerRemote()
return result
}
async function innerRemote() {
'use cache: remote'
return getData()
}
// 无效:远程缓存嵌套在私有缓存中
async function outerPrivate() {
'use cache: private'
const result = await innerRemote() // 错误!
return result
}
async function innerRemote() {
'use cache: remote'
return getData()
}
// 无效:私有缓存嵌套在远程缓存中
async function outerRemote() {
'use cache: remote'
const result = await innerPrivate() // 错误!
return result
}
async function innerPrivate() {
'use cache: private'
return getData()
}示例#
以下示例演示了使用 'use cache: remote' 的常见模式。有关 cacheLife 参数(stale、revalidate、expire)的详细信息,请参阅 cacheLife API 参考。
结合用户偏好#
根据用户偏好的货币缓存产品价格。由于货币存储在 cookie 中,该组件在请求时渲染。远程缓存在此很有价值,因为使用相同货币的所有用户共享缓存的价格,并且在无服务器环境中,所有实例共享同一个远程缓存。
import { Suspense } from 'react'
import { cookies } from 'next/headers'
import { cacheTag, cacheLife } from 'next/cache'
export async function generateStaticParams() {
return [{ id: '1' }, { id: '2' }, { id: '3' }]
}
export default async function ProductPage({
params,
}: {
params: Promise<{ id: string }>
}) {
const { id } = await params
return (
<div>
<ProductDetails id={id} />
<Suspense fallback={<div>Loading price...</div>}>
<ProductPrice productId={id} />
</Suspense>
</div>
)
}
function ProductDetails({ id }: { id: string }) {
return <div>Product: {id}</div>
}
async function ProductPrice({ productId }: { productId: string }) {
// 读取 cookies 会将该组件推迟到请求时渲染
const currency = (await cookies()).get('currency')?.value ?? 'USD'
// 按产品和货币组合缓存价格
// 使用相同货币的所有用户共享此缓存条目
const price = await getProductPrice(productId, currency)
return (
<div>
Price: {price} {currency}
</div>
)
}
async function getProductPrice(productId: string, currency: string) {
'use cache: remote'
cacheTag(`product-price-${productId}`)
cacheLife({ expire: 3600 }) // 1 小时
// 按 (productId, currency) 缓存 - 货币种类少意味着缓存利用率高
return db.products.getPrice(productId, currency)
}import { Suspense } from 'react'
import { cookies } from 'next/headers'
import { cacheTag, cacheLife } from 'next/cache'
export async function generateStaticParams() {
return [{ id: '1' }, { id: '2' }, { id: '3' }]
}
export default async function ProductPage({ params }) {
const { id } = await params
return (
<div>
<ProductDetails id={id} />
<Suspense fallback={<div>Loading price...</div>}>
<ProductPrice productId={id} />
</Suspense>
</div>
)
}
function ProductDetails({ id }) {
return <div>Product: {id}</div>
}
async function ProductPrice({ productId }) {
// 读取 cookies 会将该组件推迟到请求时渲染
const currency = (await cookies()).get('currency')?.value ?? 'USD'
// 按产品和货币组合缓存价格
// 使用相同货币的所有用户共享此缓存条目
const price = await getProductPrice(productId, currency)
return (
<div>
Price: {price} {currency}
</div>
)
}
async function getProductPrice(productId, currency) {
'use cache: remote'
cacheTag(`product-price-${productId}`)
cacheLife({ expire: 3600 }) // 1 小时
// 按 (productId, currency) 缓存 - 货币种类少意味着缓存利用率高
return db.products.getPrice(productId, currency)
}降低数据库负载#
缓存开销大的数据库查询,降低数据库负载。在此示例中,我们不访问 cookies()、headers() 或 searchParams。如果我们要求不将这些统计信息包含在静态外壳中,可以使用 connection() 显式推迟到请求时:
import { Suspense } from 'react'
import { connection } from 'next/server'
import { cacheLife, cacheTag } from 'next/cache'
export default function DashboardPage() {
return (
<Suspense fallback={<div>Loading stats...</div>}>
<DashboardStats />
</Suspense>
)
}
async function DashboardStats() {
// 推迟到请求时
await connection()
const stats = await getGlobalStats()
return <StatsDisplay stats={stats} />
}
async function getGlobalStats() {
'use cache: remote'
cacheTag('global-stats')
cacheLife({ expire: 60 }) // 1 分钟
// 这个开销大的数据库查询会被缓存并在所有用户之间共享,
// 从而降低数据库负载
const stats = await db.analytics.aggregate({
total_users: 'count',
active_sessions: 'count',
revenue: 'sum',
})
return stats
}通过此设置,无论有多少用户访问仪表板,你的上游数据库每分钟最多只收到一个请求。
流式上下文中的 API 响应#
缓存流式传输期间或动态操作之后获取的 API 响应:
import { Suspense } from 'react'
import { connection } from 'next/server'
import { cacheLife, cacheTag } from 'next/cache'
export default async function FeedPage() {
return (
<div>
<Suspense fallback={<Skeleton />}>
<FeedItems />
</Suspense>
</div>
)
}
async function FeedItems() {
// 推迟到请求时
await connection()
const items = await getFeedItems()
return items.map((item) => <FeedItem key={item.id} item={item} />)
}
async function getFeedItems() {
'use cache: remote'
cacheTag('feed-items')
cacheLife({ expire: 120 }) // 2 分钟
// 此 API 调用会被缓存,从而减少对外部服务的请求
const response = await fetch('https://api.example.com/feed')
return response.json()
}动态检查之后的计算数据#
缓存发生在动态安全检查或功能检查之后的开销大的计算:
import { connection } from 'next/server'
import { cacheLife } from 'next/cache'
export default async function ReportsPage() {
// 推迟到请求时(用于安全检查)
await connection()
const report = await generateReport()
return <ReportViewer report={report} />
}
async function generateReport() {
'use cache: remote'
cacheLife({ expire: 3600 }) // 1 小时
// 这个开销大的计算会被缓存并在所有授权用户之间共享,
// 避免重复计算
const data = await db.transactions.findMany()
return {
totalRevenue: calculateRevenue(data),
topProducts: analyzeProducts(data),
trends: calculateTrends(data),
}
}混合缓存策略#
结合静态缓存、远程缓存和私有缓存以获得最佳性能:
import { Suspense } from 'react'
import { connection } from 'next/server'
import { cookies } from 'next/headers'
import { cacheLife, cacheTag } from 'next/cache'
// 静态产品数据 - 在构建时预渲染
async function getProduct(id: string) {
'use cache'
cacheTag(`product-${id}`)
// 这在构建时缓存,并在所有用户之间共享
return db.products.find({ where: { id } })
}
// 共享价格数据 - 在运行时缓存于远程 handler 中
async function getProductPrice(id: string) {
'use cache: remote'
cacheTag(`product-price-${id}`)
cacheLife({ expire: 300 }) // 5 分钟
// 这在运行时缓存,并在所有用户之间共享
return db.products.getPrice({ where: { id } })
}
// 用户特定推荐 - 每个用户的私有缓存
async function getRecommendations(productId: string) {
'use cache: private'
cacheLife({ expire: 60 }) // 1 分钟
const sessionId = (await cookies()).get('session-id')?.value
// 这按用户缓存,从不共享
return db.recommendations.findMany({
where: { productId, sessionId },
})
}
export default async function ProductPage({ params }) {
const { id } = await params
// 静态产品数据
const product = await getProduct(id)
return (
<div>
<ProductDetails product={product} />
<Suspense fallback={<PriceSkeleton />}>
<ProductPriceComponent productId={id} />
</Suspense>
<Suspense fallback={<RecommendationsSkeleton />}>
<ProductRecommendations productId={id} />
</Suspense>
</div>
)
}
function ProductDetails({ product }) {
return (
<div>
<h1>{product.name}</h1>
<p>{product.description}</p>
</div>
)
}
async function ProductPriceComponent({ productId }) {
// 推迟到请求时
await connection()
const price = await getProductPrice(productId)
return <div>Price: ${price}</div>
}
async function ProductRecommendations({ productId }) {
const recommendations = await getRecommendations(productId)
return <RecommendationsList items={recommendations} />
}
function PriceSkeleton() {
return <div>Loading price...</div>
}
function RecommendationsSkeleton() {
return <div>Loading recommendations...</div>
}
function RecommendationsList({ items }) {
return (
<ul>
{items.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
)
}小知识:
- 远程缓存存储在服务端缓存 handler 中,并在所有用户之间共享
'use cache: remote'在静态外壳之外也能工作,而在那里use cache可能无法获得服务端缓存命中- 使用
cacheTag()和revalidateTag()按需使远程缓存失效- 使用
cacheLife()配置缓存过期时间- 对于用户特定数据,请使用
'use cache: private',而非'use cache: remote'- 远程缓存通过在服务端存储计算或获取的数据来降低源站负载
平台支持#
| 部署选项 | 是否支持 |
|---|---|
| Node.js 服务器 | 是 |
| Docker 容器 | 是 |
| 静态导出 | 否 |
| 适配器 | 是 |
版本历史#
| 版本 | 变更 |
|---|---|
v16.0.0 | "use cache: remote" 随 Cache Components 功能一同启用。 |