cacheLife
cacheLife
选项允许您在组件或函数中使用 cacheLife
函数时,以及在 use cache
指令 作用域内定义自定义缓存配置。
使用方法
要定义配置,请启用 dynamicIO
标志 并在 next.config.js
文件的 cacheLife
对象中添加缓存配置。例如,定义一个 blog
配置:
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
dynamicIO: true,
cacheLife: {
blog: {
stale: 3600, // 1 小时
revalidate: 900, // 15 分钟
expire: 86400, // 1 天
},
},
},
}
export default nextConfig
module.exports = {
experimental: {
dynamicIO: true,
cacheLife: {
blog: {
stale: 3600, // 1 小时
revalidate: 900, // 15 分钟
expire: 86400, // 1 天
},
},
},
}
现在您可以在组件或函数中使用这个自定义的 blog
配置,如下所示:
import { unstable_cacheLife as cacheLife } from 'next/cache'
export async function getCachedData() {
'use cache'
cacheLife('blog')
const data = await fetch('/api/data')
return data
}
import { unstable_cacheLife as cacheLife } from 'next/cache'
export async function getCachedData() {
'use cache'
cacheLife('blog')
const data = await fetch('/api/data')
return data
}
参考
配置对象包含以下格式的键值:
属性 | 值类型 | 描述 | 要求 |
---|---|---|---|
stale | number | 客户端在不检查服务器的情况下缓存值的持续时间。 | 可选 |
revalidate | number | 服务器上缓存刷新的频率;在重新验证期间可能会提供过期的值。 | 可选 |
expire | number | 值在切换到动态之前可以保持过期的最大持续时间。 | 可选 - 必须大于 revalidate 的值 |