Next.js缓存机制
外观
Next.js缓存机制[编辑 | 编辑源代码]
介绍[编辑 | 编辑源代码]
Next.js 缓存机制是框架内置的优化策略,用于提升应用性能并减少不必要的计算或数据请求。它通过存储渲染结果、静态资源和数据响应来加速页面加载,同时支持动态内容的实时更新。理解缓存机制对于构建高效Next.js应用至关重要,特别是在处理SSG、SSR和CSR时。
核心缓存类型[编辑 | 编辑源代码]
Next.js 包含多级缓存系统:
1. 构建时缓存(Build-time Cache)[编辑 | 编辑源代码]
在next build
阶段生成:
# 输出示例
○ /about 2.5 kB 77.8 kB
● /blog/[slug] 2.8 kB 78.1 kB (ISR: 10 seconds)
- 静态页面(
●
标记)会被缓存在CDN - 支持ISR的页面会标注重新验证时间
2. 请求时缓存(Request-time Cache)[编辑 | 编辑源代码]
通过fetch
API或路由处理器实现:
// 数据缓存示例
async function getData() {
const res = await fetch('https://api.example.com/data', {
next: { revalidate: 60 } // 每60秒重新验证
});
return res.json();
}
3. 路由缓存(Router Cache)[编辑 | 编辑源代码]
客户端内存中的临时缓存:
缓存控制策略[编辑 | 编辑源代码]
静态生成(SSG)[编辑 | 编辑源代码]
完全静态页面默认永久缓存:
export async function getStaticProps() {
return {
props: {}, // 无revalidate参数
};
}
增量静态再生(ISR)[编辑 | 编辑源代码]
混合静态+动态缓存:
export async function getStaticProps() {
return {
props: {},
revalidate: 30, // 最多每30秒更新一次
};
}
动态渲染(Dynamic Rendering)[编辑 | 编辑源代码]
完全跳过缓存:
export const dynamic = 'force-dynamic'; // 禁用所有缓存
实际案例[编辑 | 编辑源代码]
电商产品页面[编辑 | 编辑源代码]
结合ISR和客户端缓存:
// pages/products/[id].js
export async function getStaticProps({ params }) {
const product = await getProductFromDB(params.id);
return {
props: { product },
revalidate: 3600, // 每小时重新生成
};
}
export async function getStaticPaths() {
return {
paths: [],
fallback: 'blocking', // 动态路径按需生成
};
}
实时仪表盘[编辑 | 编辑源代码]
短周期缓存+客户端轮询:
// 组件内
useEffect(() => {
const interval = setInterval(() => {
fetch('/api/metrics', { cache: 'no-store' })
.then(res => res.json())
.then(updateMetrics);
}, 5000);
return () => clearInterval(interval);
}, []);
高级配置[编辑 | 编辑源代码]
自定义缓存键[编辑 | 编辑源代码]
通过unstable_cache
API:
import { unstable_cache } from 'next/cache';
const getData = unstable_cache(
async () => db.query('SELECT * FROM posts'),
['all-posts'],
{ revalidate: 60 }
);
缓存清除[编辑 | 编辑源代码]
使用路由处理器:
// app/api/revalidate/route.js
export async function POST(request) {
const { path } = await request.json();
revalidatePath(path);
return Response.json({ revalidated: true });
}
数学原理[编辑 | 编辑源代码]
缓存效率可通过命中率计算:
理想ISR场景下的成本节省:
最佳实践[编辑 | 编辑源代码]
- 静态内容使用SSG+长期缓存
- 频繁更新内容采用ISR+短周期验证
- 实时数据结合
cache: 'no-store'
- 监控缓存命中率调整策略
常见问题[编辑 | 编辑源代码]
Q: 如何强制清除特定路由缓存?
A: 使用revalidatePath
或revalidateTag
API
Q: 开发模式缓存行为是否不同?
A: 是的,开发模式下默认禁用大多数缓存,可通过next dev --no-cache
显式控制
Q: 如何验证缓存是否生效?
A: 检查响应头中的x-nextjs-cache
字段:
HTTP/1.1 200 OK
x-nextjs-cache: HIT