实战案例
案例:博客系统
// lib/api.ts
export async function getPosts() {
const res = await fetch('https://api.example.com/posts', {
next: {
revalidate: 3600, // 每小时更新
tags: ['posts'] // 打标签
}
});
return res.json();
}
export async function getPost(id: string) {
const res = await fetch(`https://api.example.com/posts/${id}`, {
next: {
revalidate: 3600,
tags: ['posts', `post-${id}`] // 多个标签
}
});
return res.json();
}
// app/actions.ts
'use server';
import { updateTag } from 'next/cache';
export async function createPost(formData: FormData) {
// 1. 创建文章
await db.post.create({ data: { ... } });
// 2. 立即失效列表缓存(用户提交后立刻看到新文章)
updateTag('posts');
}
export async function updatePost(id: string, formData: FormData) {
// 1. 更新文章
await db.post.update({ where: { id }, data: { ... } });
// 2. 立即失效列表和详情缓存
updateTag('posts');
updateTag(`post-${id}`);
}
如果是在 Route Handler 中(比如接收 webhook),则使用 revalidateTag: