
缓存机制可以分为两种类型:全局缓存和页面缓存。全局缓存适用于需要频繁访问的数据,而页面缓存则适用于需要缓存的页面内容。我们可以通过使用 `getStaticProps` 和 `getServerSideProps` 函数来实现缓存。
使用缓存机制可以带来显著的性能提升,例如可以减少服务器的负载和响应时间。
Next.js 缓存
缓存机制包括 Request Memoization、Data Cache、Full Route Cache 和 Router Cache。每种机制都有其特点和应用场景。
Request Memoization 是一种内存缓存机制,用于缓存请求的结果。它在 Next.js 中用于缓存路由的渲染结果和 HTML。缓存结果会在下一次请求时被重用。
Data Cache 是一种用于缓存数据的机制。它可以用于缓存静态数据和动态数据。缓存数据会在下一次请求时被重用。
Full Route Cache 是一种用于缓存完整路由的机制。它会缓存路由的渲染结果和 HTML。缓存结果会在下一次请求时被重用。
Router Cache 是一种用于缓存路由器快取的机制。它会缓存路由器快取中的数据。缓存数据会在下一次请求时被重用。
以下是缓存机制的比较:
缓存机制可以通过以下方式失效:
- 重新验证数据:重新验证数据会使缓存失效。
- 重新部署:重新部署会清除缓存。
- 使用动态 API:使用动态 API 会使缓存失效。
- 使用 `dynamic = 'force-dynamic'` 或 `revalidate = 0` 路由区段设置选项:会使缓存失效。
缓存机制也可以通过以下方式管理:
- 使用 `router.refresh` 方法:会清除缓存并向服务器发送新的请求。
- 使用 `revalidateTag` 方法:会清除与指定标签关联的缓存。
- 使用 `revalidatePath` 方法:会清除指定路径的缓存。
Next.js
Next.js is a powerful framework for building server-rendered React applications, and one of its key features is caching. By default, Next.js caches the rendered output of routes, which can improve performance and reduce the number of requests to the server.
The cache is stored in the browser's memory and is divided into four distinct caching mechanisms: request memoization, data cache, full route cache, and router cache. Each of these mechanisms has its own role, storage location, and duration.
The full route cache is a server-side cache that stores the rendered output of routes, including React server components and HTML. This cache is enabled by default and is responsible for storing the rendered output of static routes. However, dynamic routes are not cached by default and are instead rendered on the fly.
You can opt out of the full route cache by using the `dynamic` or `revalidate` options on a route, which will render the component and fetch data on every request. Alternatively, you can disable the data cache on a specific fetch request, which will cause the route to be rendered on every request.
Here are the four caching mechanisms in Next.js, summarized:
You can invalidate the cache by using the `router.refresh()` method, which will clear the router cache and fetch the current route from the server. Alternatively, you can use the `revalidatePath` or `revalidateTag` methods to invalidate the cache for a specific path or tag.
Finally, you can use the `prefetch` option on the `Link` component to prefetch the next route, which can improve performance by reducing the number of requests to the server. However, this will not permanently skip the cache, and the route will still be cached on the client-side.
Curious to learn more? Check out: Next Js Api Call
缓存机制
缓存机制是 Next.js 优化性能的关键组成部分。 Next.js 有四种缓存机制,每种机制都有不同的作用和存储位置。
缓存机制包括 Request Memoization、Data Cache、Full Route Cache 和 Router Cache。每种机制都有不同的作用和存储位置。
Request Memoization 是 Next.js 缓存机制中的一种,用于缓存请求的结果。它会将请求的结果存储在内存中,以便于下一次请求时直接从缓存中获取结果。缓存结果的有效期取决于 Session 和自动失效期限。
Data Cache 是 Next.js 缓存机制中的一种,用于缓存页面的数据。它会将页面的数据存储在内存中,以便于下一次请求时直接从缓存中获取数据。缓存数据的有效期取决于 Session 和自动失效期限。
Full Route Cache 是 Next.js 缓存机制中的一种,用于缓存整个路由的渲染结果。它会将整个路由的渲染结果存储在内存中,以便于下一次请求时直接从缓存中获取结果。缓存结果的有效期取决于 Session 和自动失效期限。
Router Cache 是 Next.js 缓存机制中的一种,用于缓存路由器的快取。它会将路由器的快取存储在内存中,以便于下一次请求时直接从缓存中获取快取。
缓存机制的有效期取决于 Session 和自动失效期限。Session 是指用户的会话,自动失效期限是指缓存结果的有效期。缓存机制的失效方式包括重新验证数据、重新部署和手动失效。
以下是缓存机制的失效方式:
- 重新验证数据:重新验证数据会使缓存失效,缓存结果会被重新渲染。
- 重新部署:重新部署会清除缓存,缓存结果会被重新渲染。
- 手动失效:手动失效会清除缓存,缓存结果会被重新渲染。
缓存机制的优点包括提高性能、减少请求次数和提高用户体验。缓存机制的缺点包括增加内存占用和缓存失效的复杂性。
以下是缓存机制的优点和缺点:
缓存机制的应用场景包括静态站点生成、动态站点生成和实时应用。缓存机制的适用场景包括要求高性能和快速响应的场景。
以下是缓存机制的应用场景:
缓存机制的设置和管理包括设置缓存有效期、设置缓存失效方式和管理缓存结果。缓存机制的设置和管理需要考虑缓存机制的优点和缺点。
以下是缓存机制的设置和管理:
缓存机制的最佳实践包括设置缓存有效期、设置缓存失效方式和管理缓存结果。缓存机制的最佳实践需要考虑缓存机制的优点和缺点。
以下是缓存机制的最佳实践:
非 Fetch 请求
In Next.js, you can cache non-fetch requests using React's cache function. This allows you to cache database requests, for example.
To do this, you need to pass the function you want to cache to the cache function, which will return a memoized version of that function. This means the data will be retrieved from the cache the next time the function is called with the same input.
The cache is only valid for the duration of a single render pass, so you don't have to worry about revalidation like you would with a persistent cache.
Expand your knowledge: Next Js Function Handlers to Filter Data
Fetchlet Data = Await Fetch('https://api.vercel.app/blog')
Fetchlet Data is a clever way to reuse cached data in React, and it's especially useful when you need to display the same information in multiple places on the same page.
This is where Request Memoization comes in, a React feature that caches every fetch request made in a server component during the render cycle. This means that if you make a fetch request in one component and then make the same fetch request in another component, the second fetch request will not actually make a request to the server.
The cache is stored entirely on the server, which is why it's only valid for the duration of a single render cycle. This is not an issue, though, as the entire purpose of this cache is to reduce duplicate fetch requests within a single render cycle.
Fetchlet Data uses this cache to store and reuse data, making it a great tool for optimizing your application's performance. By reusing cached data, you can drastically increase the performance of your application by reducing the number of requests made to your server.
Broaden your view: Nextjs Components Library
Non-Fetch Requests
React only caches fetch requests by default, but you can cache other types of requests like database requests using React's cache function.

To cache a function, you simply pass it to the cache function, and it will return a memoized version of that function. This is exactly what's done in the code where fetchUserData() is cached.
The memoization is valid only for the duration of a single render pass and works the same way as fetch memoization. This means the data is retrieved from the cache the next time the function is called with the same input.
Revalidation is not a concern with Request Memoization because the cache is only valid for the duration of a single request, so you never have to worry about it becoming stale.
Data
Data Cache 是一个非常有用的特性,它可以帮助我们避免不必要的 API 请求,从而提高应用的性能。例如,如果我们有一个页面,它需要从 API 获取关于某个城市的指南数据,而这类数据通常不会经常更新,那么我们可以使用 Data Cache 将这些数据缓存起来,以便在用户访问该页面时直接从缓存中获取。
我们可以使用 on-demand revalidation 来重新验证缓存的数据,只有当有新的数据可用时才会重新验证。这对于需要在数据更新时重新获取最新数据的场景非常有用。例如,我们可以在某个事件发生时重新验证缓存的数据,以便获取最新的数据。
我们可以使用 revalidatePath 函数来清除 Data Cache 中的缓存数据。这个函数接受一个字符串路径作为参数,并且会清除所有与该路径相关的缓存数据。
我们也可以使用 revalidateTag 函数来清除 Data Cache 中特定标签的缓存数据。这个函数接受一个字符串标签作为参数,并且会清除所有与该标签相关的缓存数据。
如果我们需要在整个页面上禁用 Data Cache,那么我们可以在页面的顶级配置中添加一个 segment config 选项。这个选项会将页面设为动态页面,并且会禁用 Data Cache。
我们还可以使用 revalidate segment config 选项来禁用 Data Cache。在这种情况下,我们需要将其设置为 0。
我们可以使用 cache 选项来配置 Data Cache 的行为。例如,我们可以将 cache 选项设置为 'no-store' 来禁用 Data Cache。
在 Next.js 中,我们可以使用 Data Cache 来缓存 API 请求的结果。例如,我们可以在 getGuides 函数中缓存指南数据,然后使用 getCachedGuides 函数来获取缓存的数据。
Duration
When using Next.js, you can control the duration of cached data with the `maxAge` option. This option specifies the maximum age of the cached response in seconds.
The default value for `maxAge` is 0, which means the cached response is refreshed on every request. However, you can set a specific value to control how long the cached response remains valid. For example, setting `maxAge` to 3600 would cache the response for 1 hour.
In some cases, you may want to use a more dynamic approach, such as using a cookie to store the cache expiration time.
路由
Full Route Cache 有一个很重要的特性:它会在重新部署应用程序时清除缓存。所以,如果您重新部署应用程序,缓存将会被清除。
Router Cache 是一种客户端缓存,存储在浏览器中。它缓存用户访问过的路由,下次用户访问这些路由时会直接从缓存中取出,而不需要再次请求服务器。Router Cache 的缓存时间取决于路由类型:静态路由缓存 5 分钟,而动态路由缓存 30 秒。
Router Cache 还有一个重要特性:它只缓存用户当前会话中的数据。所以,如果用户关闭浏览器或刷新页面,缓存将会被清除。
您可以通过调用 `revalidatePath` 或 `revalidateTag` 来手动重新验证 Router Cache,也可以通过 `router.refresh` 函数来重新验证缓存。
不稳定 API
Next.js 的不稳定 API 是一个低级缓存 API,允许我们对缓存有更细粒度的控制。它是 Next.js 缓存 API 的一部分,但还不稳定,可能会在将来改变。
这个 API 是通过 `unstable_cache` 函数来访问的,它必须返回一个 Promise。我们可以通过传递一个函数、一个 keys 数组和一个 options 对象来调用它。options 对象允许我们控制一些缓存的细节,例如添加标签来后续无效缓存,或者传递一个 revalidate 参数,指定缓存应该在多长时间后重新验证。
使用不稳定 API,我们可以缓存数据库查询或 API 调用的结果。例如,我们可以使用它来缓存一个数据库查询的结果,如下所示:
```javascript
unstable_cache(getUser, ['user'], { tags: ['user'], revalidate: 60 });
```
这个例子中,我们使用 `unstable_cache` 函数来缓存 `getUser` 函数的结果,并传递一个 keys 数组和一个 options 对象。options 对象中,我们指定了标签 `['user']` 和重新验证时间 `60` 秒。
注意 `unstable_cache` 返回一个函数,我们需要调用这个函数来获取缓存的数据。
Expand your knowledge: Nextjs Revalidate
Sources
- https://nextjs.dev.org.tw/docs/app/building-your-application/caching
- https://nextjs.org/docs/app/building-your-application/caching
- https://blog.webdevsimplified.com/2024-01/next-js-app-router-cache/
- https://blog.logrocket.com/caching-next-js-unstable-cache/
- https://nextjscn.org/docs/app/building-your-application/caching
Featured Images: pexels.com