Skip to main content

cacheLife

cacheLife 函数用于设置函数或组件的缓存生存期。它应与 use cache 指令一起使用,并在函数或组件的范围内。

¥The cacheLife function is used to set the cache lifetime of a function or component. It should be used alongside the use cache directive, and within the scope of the function or component.

用法

¥Usage

要使用 cacheLife,请在 next.config.js 文件中启用 dynamicIO 标志

¥To use cacheLife, enable the dynamicIO flag in your next.config.js file:

import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
experimental: {
dynamicIO: true,
},
}

export default nextConfig
const nextConfig = {
experimental: {
dynamicIO: true,
},
}

export default nextConfig

然后,在函数或组件的范围内导入并调用 cacheLife 函数:

¥Then, import and invoke The cacheLife function within the scope of the function or component:

'use cache'
import { unstable_cacheLife as cacheLife } from 'next/cache'

export default async function Page() {
cacheLife('hours')
return <div>Page</div>
}
'use cache'
import { unstable_cacheLife as cacheLife } from 'next/cache'

export default async function Page() {
cacheLife('hours')
return <div>Page</div>
}

参考

¥Reference

默认缓存配置文件

¥Default cache profiles

Next.js 提供了一组以各种时间尺度为模型的命名缓存配置文件。如果你没有在 cacheLife 函数中与 use cache 指令一起指定缓存配置文件,Next.js 将自动应用“默认”缓存配置文件。

¥Next.js provides a set of named cache profiles modeled on various timescales. If you don't specify a cache profile in the cacheLife function alongside the use cache directive, Next.js will automatically apply the “default” cache profile.

但是,我们建议在使用 use cache 指令明确定义缓存行为时始终添加缓存配置文件。

¥However, we recommend always adding a cache profile when using the use cache directive to explicitly define caching behavior.

配置文件过时重新验证过期描述
defaultundefined15 分钟INFINITE_CACHE默认配置文件,适用于不需要频繁更新的内容
secondsundefined1 秒1 分钟对于需要近乎实时更新的快速变化的内容
minutes5 分钟1 分钟1 小时对于一小时内频繁更新的内容
hours5 分钟1 小时1 天对于每天更新但可能略显陈旧的内容
days5 分钟1 天1 周对于每周更新但可能已过时的内容
weeks5 分钟1 周1 个月对于每月更新但可能已过时的内容
max5 分钟1 个月INFINITE_CACHE对于很少需要更新的非常稳定的内容

用于引用缓存配置文件的字符串值不具有固有含义;相反,它们用作语义标签。这使你能够更好地理解和管理代码库中的缓存内容。

¥The string values used to reference cache profiles don't carry inherent meaning; instead they serve as semantic labels. This allows you to better understand and manage your cached content within your codebase.

自定义缓存配置文件

¥Custom cache profiles

你可以通过将自定义缓存配置文件添加到 next.config.ts 文件中的 cacheLife 选项来配置它们。

¥You can configure custom cache profiles by adding them to the cacheLife option in your next.config.ts file.

缓存配置文件是包含以下属性的对象:

¥Cache profiles are objects that contain the following properties:

属性描述要求
stalenumber客户端应缓存值而不检查服务器的持续时间。可选的
revalidatenumber缓存在服务器上刷新的频率;重新验证时可能会提供过时的值。可选的
expirenumber在切换到动态获取之前,值可以保持陈旧的最长持续时间;必须长于 revalidate可选的 - 必须比 revalidate

"stale" 属性与 staleTimes 设置的不同之处在于它专门控制客户端路由缓存。虽然 staleTimes 是一个影响动态和静态数据所有实例的全局设置,但 cacheLife 配置允许你在每个函数或每个路由的基础上定义 "stale" 次。

¥The "stale" property differs from the staleTimes setting in that it specifically controls client-side router caching. While staleTimes is a global setting that affects all instances of both dynamic and static data, the cacheLife configuration allows you to define "stale" times on a per-function or per-route basis.

很高兴知道:“stale”属性未设置 Cache-control: max-age 标头。它反而控制客户端路由缓存。

¥Good to know: The “stale” property does not set the Cache-control: max-age header. It instead controls the client-side router cache.

示例

¥Examples

定义可重用缓存配置文件

¥Defining reusable cache profiles

你可以在 next.config.ts 文件中定义它们来创建可重复使用的缓存配置文件。选择适合你用例的名称并设置 stalerevalidateexpire 属性的值。你可以根据需要创建任意数量的自定义缓存配置文件。每个配置文件都可以通过其名称作为传递给 cacheLife 函数的字符串值来引用。

¥You can create a reusable cache profile by defining them in your next.config.ts file. Choose a name that suits your use case and set values for the stale, revalidate, and expire properties. You can create as many custom cache profiles as needed. Each profile can be referenced by its name as a string value passed to the cacheLife function.

import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
experimental: {
dynamicIO: true,
cacheLife: {
biweekly: {
stale: 60 * 60 * 24 * 14, // 14 days
revalidate: 60 * 60 * 24, // 1 day
expire: 60 * 60 * 24 * 14, // 14 days
},
},
},
}

module.exports = nextConfig
const nextConfig = {
experimental: {
dynamicIO: true,
cacheLife: {
biweekly: {
stale: 60 * 60 * 24 * 14, // 14 days
revalidate: 60 * 60 * 24, // 1 day
expire: 60 * 60 * 24 * 14, // 14 days
},
},
},
}

module.exports = nextConfig

上述示例缓存 14 天,每天检查更新,并在 14 天后使缓存过期。然后,你可以通过其名称在整个应用中引用此配置文件:

¥The example above caches for 14 days, checks for updates daily, and expires the cache after 14 days. You can then reference this profile throughout your application by its name:

'use cache'
import { unstable_cacheLife as cacheLife } from 'next/cache'

export default async function Page() {
cacheLife('biweekly')
return <div>Page</div>
}

覆盖默认值缓存配置文件

¥Overriding the default cache profiles

虽然默认缓存配置文件提供了一种有用的方法来思考可缓存输出的任何给定部分的新鲜度或陈旧度,但你可能更喜欢使用不同命名的配置文件来更好地与你的应用缓存策略保持一致。

¥While the default cache profiles provide a useful way to think about how fresh or stale any given part of cacheable output can be, you may prefer different named profiles to better align with your applications caching strategies.

你可以通过创建与默认配置同名的新配置来覆盖默认的命名缓存配置文件。

¥You can override the default named cache profiles by creating a new configuration with the same name as the defaults.

以下示例显示如何覆盖默认的“天”缓存配置文件:

¥The example below shows how to override the default “days” cache profile:

const nextConfig = {
experimental: {
dynamicIO: true,
cacheLife: {
days: {
stale: 3600, // 1 hour
revalidate: 900, // 15 minutes
expire: 86400, // 1 day
},
},
},
}

module.exports = nextConfig

内联定义缓存配置文件

¥Defining cache profiles inline

对于特定用例,你可以通过将对象传递给 cacheLife 函数来设置自定义缓存配置文件:

¥For specific use cases, you can set a custom cache profile by passing an object to the cacheLife function:

'use cache'
import { unstable_cacheLife as cacheLife } from 'next/cache'

export default async function Page() {
cacheLife({
stale: 3600, // 1 hour
revalidate: 900, // 15 minutes
expire: 86400, // 1 day
})

return <div>Page</div>
}
'use cache'
import { unstable_cacheLife as cacheLife } from 'next/cache'

export default async function Page() {
cacheLife({
stale: 3600, // 1 hour
revalidate: 900, // 15 minutes
expire: 86400, // 1 day
})

return <div>Page</div>
}

此内联缓存配置文件仅适用于创建它的函数或文件。如果你想在整个应用中重复使用相同的配置文件,你可以将 添加配置 添加到 next.config.ts 文件的 cacheLife 属性。

¥This inline cache profile will only be applied to the function or file it was created in. If you want to reuse the same profile throughout your application, you can add the configuration to the cacheLife property of your next.config.ts file.

use cachecacheLife 的嵌套使用

¥Nested usage of use cache and cacheLife

在同一路由或组件树中定义多个缓存行为时,如果内部缓存指定了自己的 cacheLife 配置文件,则外部缓存将遵循其中最短的缓存持续时间。这仅适用于外部缓存没有定义自己的显式 cacheLife 配置文件的情况。

¥When defining multiple caching behaviors in the same route or component tree, if the inner caches specify their own cacheLife profile, the outer cache will respect the shortest cache duration among them. This applies only if the outer cache does not have its own explicit cacheLife profile defined.

例如,如果你将 use cache 指令添加到页面,而不指定缓存配置文件,则将隐式应用默认缓存配置文件(cacheLife(”default”))。如果导入到页面中的组件也使用具有其自己的缓存配置文件的 use cache 指令,则会比较外部和内部缓存配置文件,并应用配置文件中设置的最短持续时间。

¥For example, if you add the use cache directive to your page, without specifying a cache profile, the default cache profile will be applied implicitly (cacheLife(”default”)). If a component imported into the page also uses the use cache directive with its own cache profile, the outer and inner cache profiles are compared, and shortest duration set in the profiles will be applied.

// Parent component
import { unstable_cacheLife as cacheLife } from 'next/cache'
import { ChildComponent } from './child'

export async function ParentComponent() {
'use cache'
cacheLife('days')

return (
<div>
<ChildComponent />
</div>
)
}

并且在一个单独的文件中,我们定义了导入的子组件:

¥And in a separate file, we defined the Child component that was imported:

// Child component
import { unstable_cacheLife as cacheLife } from 'next/cache'

export async function ChildComponent() {
'use cache'
cacheLife('hours')
return <div>Child Content</div>

// This component's cache will respect the shorter 'hours' profile
}