use cache: remote
了解如何使用 "use cache: remote" 指令,通过远程缓存处理器实现持久化、共享的缓存。
虽然 use cache 指令足以满足大多数应用需求,但你可能会注意到缓存操作重新执行的频率高于预期,或者上游服务(CMS、数据库、外部 API)收到的请求比你预期的更多。这是因为 use cache 将条目存储在内存中,而这存在固有的局限性:
- 缓存条目被逐出以腾出空间存放新条目
- 部署环境的内存限制
- 缓存无法在请求之间或服务器重启后持久保留
请注意,use cache 除了服务器端缓存之外仍然具有价值:它告知 Next.js 哪些内容可以预取,并为客户端导航定义过期时间。
'use cache: remote' 指令让你可以声明式地指定缓存输出应存储在远程缓存中而非内存中,从而提供在所有服务器实例之间共享的持久化缓存。这也会带来权衡:基础设施成本以及缓存查找期间的网络延迟。
用法
要使用 'use cache: remote',请在 next.config.ts 文件中启用 cacheComponents 标志:
TypeScript
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
}
export default nextConfig
JavaScript
/** @type {import('next').NextConfig} */
const nextConfig = {
cacheComponents: true,
}
module.exports = nextConfig
然后在你确定值得使用远程缓存的函数或组件中添加 'use cache: remote'。处理器实现通过 cacheHandlers 配置,不过托管服务提供商通常会自动提供。如果你是自托管,请参阅 cacheHandlers 配置参考来设置缓存存储。
何时应避免远程缓存
- 如果你已经有一个包裹数据层的服务器端缓存键值存储,那么
use cache可能就足以将数据纳入静态外壳,而无需再增加一层缓存 - 如果由于距离近或本地访问,操作已经很快(< 50ms),那么远程缓存查找可能不会提升性能
- 如果缓存键在每个请求中大多是唯一值(搜索筛选条件、价格区间、用户特定参数),缓存利用率将接近于零
- 如果数据变化频繁(秒级到分钟级),缓存命中会很快过期,导致频繁未命中并等待上游重新验证
何时适合使用远程缓存
当内容被推迟到请求阶段(静态外壳之外)时,远程缓存的价值最大。这通常发生在组件访问 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' |
|---|---|---|---|
| 服务端缓存 | 内存中或缓存处理器 | 远程缓存处理器 | 无 |
| 缓存范围 | 所有用户共享 | 所有用户共享 | 每个客户端(浏览器) |
| 可直接访问 cookies/headers | 否(必须作为参数传入) | 否(必须作为参数传入) | 是 |
| 服务器缓存利用率 | 在静态外壳之外可能较低 | 高(跨实例共享) | N/A |
| 额外成本 | 无 | 基础设施(存储、网络) | 无 |
| 延迟影响 | 无 | 缓存处理器查找 | 无 |
| 跨部署持久化 | 否 | 否 | N/A |
跨部署持久化
远程缓存条目不会跨部署持久化。缓存键包含 deploymentId(在已配置时)或 buildId,因此新的构建会产生新的键,先前构建的条目将无法再被访问。完整的键组成请参见缓存键。
这是有意为之。在不同构建之间,函数的标识哈希或其返回值的结构可能会发生变化。升级 CMS 客户端、重构被缓存的函数或更改依赖项,都可能产生与旧调用方预期不匹配的值,因此跨部署复用条目有提供过期或格式错误数据的风险。
如果你需要跨部署持久化的条目,请对非 fetch 函数使用 unstable_cache,或者依赖 fetch 缓存。
使用运行时数据进行缓存
use cache 和 'use cache: remote' 都无法直接访问 cookies 或 search params 等运行时值。你可以提取这些值,并将其作为参数传递给被缓存的函数。此模式请参见结合运行时数据。
须知:
use cache将条目存储在内存中。在无服务器环境中,内存不会在实例之间共享,并且通常在处理完请求后就会被销毁,这会导致运行时缓存频繁未命中。
缓存键注意事项
请慎重考虑缓存键中包含哪些值。每个唯一值都会创建一个单独的缓存条目,从而降低缓存利用率。请看下面这个使用搜索筛选器的示例:
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
// Cache only on category (few unique values)
// Don't include price filter (many unique values)
const products = await getProductsByCategory(category)
// Filter price in memory instead of creating cache entries
// for every price value
const filtered = minPrice
? products.filter((p) => p.price >= parseFloat(minPrice))
: products
return <div>{/* render filtered products */}</div>
}
async function getProductsByCategory(category: string) {
'use cache: remote'
// Only category is part of the cache key
// Much better utilization than caching every price filter value
return db.products.findByCategory(category)
}
在此示例中,远程处理器为每个缓存条目存储更多数据(某个类别中的所有产品),以获得更高的缓存命中率。当缓存未命中的成本(访问你的后端)超过较大条目的存储成本时,这样做是值得的。
同样的原则也适用于用户特定数据。与其直接按用户缓存数据,不如使用用户偏好来确定要缓存哪些共享数据。
例如,如果用户的会话中包含语言偏好,请提取该偏好并用它来缓存共享内容:
- 不要使用远程缓存
getUserProfile(sessionID)(它会为每个用户创建一个条目) - 使用远程缓存
getCMSContent(language)为每种语言创建一个条目
import { cookies } from 'next/headers'
import { cacheLife } from 'next/cache'
export async function WelcomeMessage() {
// Extract the language preference (not unique per user)
const language = (await cookies()).get('language')?.value || 'en'
// Cache based on language (few unique values: en, es, fr, de, etc.)
// All users who prefer 'en' share the same cache entry
const content = await getCMSContent(language)
return <div>{content.welcomeMessage}</div>
}
async function getCMSContent(language: string) {
'use cache: remote'
cacheLife({ expire: 3600 })
// Creates ~10-50 cache entries (one per language)
// instead of thousands (one per user)
return cms.getHomeContent(language)
}
这样,所有偏好同一语言的用户共享同一个缓存条目,从而提高缓存利用率并减轻 CMS 的负载。
两个示例中的模式相同:找到唯一值较少的维度(分类与价格、语言与用户 ID),在该维度上进行缓存,然后在内存中过滤或选择其余部分。
如果 getUserProfile 使用的服务无法随前端负载扩展,你仍可以使用 use cache 指令配合较短的 cacheLife 进行内存缓存。不过,对于大多数用户数据,你很可能希望直接从源获取(如上述指南所述,源可能已经包装在键/值存储中)。
只有在有合规要求或无法重构以将运行时数据作为参数传递时,才使用 'use cache: private'。
嵌套规则
远程缓存有特定的嵌套规则:
- 远程缓存可以嵌套在其他远程缓存内(
'use cache: remote') - 远程缓存可以嵌套在常规缓存内(
'use cache') - 远程缓存不能嵌套在私有缓存内(
'use cache: private') - 私有缓存不能嵌套在远程缓存内
// VALID: Remote inside remote
async function outerRemote() {
'use cache: remote'
const result = await innerRemote()
return result
}
async function innerRemote() {
'use cache: remote'
return getData()
}
// VALID: Remote inside regular cache
async function outerCache() {
'use cache'
// The inner remote cache will work when deferred to request time
const result = await innerRemote()
return result
}
async function innerRemote() {
'use cache: remote'
return getData()
}
// INVALID: Remote inside private
async function outerPrivate() {
'use cache: private'
const result = await innerRemote() // Error!
return result
}
async function innerRemote() {
'use cache: remote'
return getData()
}
// INVALID: Private inside remote
async function outerRemote() {
'use cache: remote'
const result = await innerPrivate() // Error!
return result
}
async function innerPrivate() {
'use cache: private'
return getData()
}
示例
以下示例展示了使用 'use cache: remote' 的常见模式。有关 cacheLife 参数(stale、revalidate、expire)的详细信息,请参阅 cacheLife API 参考。
结合用户偏好
根据用户的货币偏好缓存产品定价。由于货币存储在 cookie 中,此组件在请求时渲染。远程缓存在这里很有价值,因为所有使用相同货币的用户共享缓存的定价,而且在无服务器环境中,所有实例共享同一个远程缓存。
TypeScript
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 }) {
// Reading cookies defers this component to request time
const currency = (await cookies()).get('currency')?.value ?? 'USD'
// Cache the price per product and currency combination
// All users with the same currency share this cache entry
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 hour
// Cached per (productId, currency) - few currencies means high cache utilization
return db.products.getPrice(productId, currency)
}
JavaScript
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 }) {
// Reading cookies defers this component to request time
const currency = (await cookies()).get('currency')?.value ?? 'USD'
// Cache the price per product and currency combination
// All users with the same currency share this cache entry
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 hour
// Cached per (productId, currency) - few currencies means high cache utilization
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() {
// Defer to request time
await connection()
const stats = await getGlobalStats()
return <StatsDisplay stats={stats} />
}
async function getGlobalStats() {
'use cache: remote'
cacheTag('global-stats')
cacheLife({ expire: 60 }) // 1 minute
// This expensive database query is cached and shared across all users,
// reducing load on your database
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() {
// Defer to request time
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 minutes
// This API call is cached, reducing requests to your external service
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() {
// Defer to request time (for security check)
await connection()
const report = await generateReport()
return <ReportViewer report={report} />
}
async function generateReport() {
'use cache: remote'
cacheLife({ expire: 3600 }) // 1 hour
// This expensive computation is cached and shared across all authorized users,
// avoiding repeated calculations
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'
// Static product data - prerendered at build time
async function getProduct(id: string) {
'use cache'
cacheTag(`product-${id}`)
// This is cached at build time and shared across all users
return db.products.find({ where: { id } })
}
// Shared pricing data - cached at runtime in remote handler
async function getProductPrice(id: string) {
'use cache: remote'
cacheTag(`product-price-${id}`)
cacheLife({ expire: 300 }) // 5 minutes
// This is cached at runtime and shared across all users
return db.products.getPrice({ where: { id } })
}
// User-specific recommendations - private cache per user
async function getRecommendations(productId: string) {
'use cache: private'
cacheLife({ expire: 60 }) // 1 minute
const sessionId = (await cookies()).get('session-id')?.value
// This is cached per-user and never shared
return db.recommendations.findMany({
where: { productId, sessionId },
})
}
export default async function ProductPage({ params }) {
const { id } = await params
// Static product data
const product = await getProduct(id)
return (
<div>
<ProductDetails product={product} />
{/* Dynamic shared price */}
<Suspense fallback={<PriceSkeleton />}>
<ProductPriceComponent productId={id} />
</Suspense>
{/* Dynamic personalized recommendations */}
<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 }) {
// Defer to request time
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>
)
}
须知:
- 远程缓存存储在服务器端缓存处理器中,并在所有用户之间共享
'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 功能启用。 |
相关内容
查看相关 API 参考。
- use cache:了解如何使用 "use cache" 指令在 Next.js 应用中缓存数据。
- use cache: private:了解如何使用 "use cache: private" 指令缓存访问运行时请求 API 的函数。
- cacheComponents:了解如何在 Next.js 中启用 cacheComponents 标志。
- cacheHandlers:为 Next.js 中的 use cache 指令配置自定义缓存处理器。
- cacheLife:了解如何使用 cacheLife 函数为缓存的函数或组件设置缓存过期时间。
- cacheTag:了解如何使用 cacheTag 函数在 Next.js 应用中管理缓存失效。
- connection:connection 函数的 API 参考。