缓存API Cache API

Nitro 提供了一个建立在[存储层]之上的强大的缓存系统。

它将数据存储在“缓存”挂载点中。

要覆盖生产存储,请使用 storage 选项设置 cache 挂载点:

ts
nitro.config.ts
ts
import { defineNitroConfig } from 'nitropack/config'

export default defineNitroConfig({
  storage: {
    cache: {
      driver: 'redis',
      /* redis connector options */
    }
  }
})

要在开发中覆盖 cache 挂载点,请使用 devStorage 选项添加 cache 挂载点。

Usage

ts
Router Handler
ts
// Cache an API handler
export default cachedEventHandler((event) => {
  // My event handler
}, options)

Examples

如果你来自 Nuxt,下面的所有示例都应该放在 server/ 目录中。

Route Handler

缓存具有 stale-while-revalidate 行为的路由 10 秒:

routes/cached.ts
ts
export default cachedEventHandler(async () => {
  return `Response generated at ${new Date().toISOString()}`
}, {
  swr: true,
  maxAge: 10
})

响应将被缓存 10 秒,当缓存在后台更新时,一个过时的值将被发送到客户端。

缓存的答案将存储在 .nitro/cache/handlers/_/*.json 中的开发中。 缓存 1 小时获取存储库 GitHub 星数的函数的结果:

Function

响应将被缓存 10 秒,当缓存在后台更新时,一个过时的值将被发送到客户端。

缓存的答案将存储在 .nitro/cache/handlers/_/*.json 中的开发中。 缓存 1 小时获取存储库 GitHub 星数的函数的结果:

ts
utils/github.ts
ts
export const cachedGHStars = cachedFunction(async (repo: string) => {
  const data: any = await $fetch(`https://api.github.com/repos/${repo}`)

  return data.stargazers_count
}, {
  maxAge: 60 * 60,
  name: 'ghStars',
  getKey: (repo: string) => repo
})

星星将在开发中缓存在 .nitro/cache/functions/ghStars/<owner>/<repo>.json 中,“value”是星星的数量。

json
{ "expires": 1677851092249, "value": 43991, "mtime": 1677847492540, "integrity": "ZUHcsxCWEH" }

Route Rules

此功能使您能够直接在主配置文件中添加基于 glob 模式的缓存路由。

此功能仍处于试验阶段,可能会在未来发展。

使用 stale-while-revalidate 行为将所有博客路由缓存 1 小时:

ts
nitro.config.ts
ts
import { defineNitroConfig } from 'nitropack/config'

export default defineNitroConfig({
  routeRules: {
    '/blog/**': {
      swr: 60 * 60,
      // or
      cache: {
        maxAge: 60 * 60
      }
    },
  },
})

如果我们想使用自定义存储挂载点,我们可以使用 base 选项。 让我们将博客路由的缓存结果存储在 Redis 存储中以用于生产:

ts
nitro.config.ts
ts
import { defineNitroConfig } from 'nitropack/config'

export default defineNitroConfig({
  storage: {
    redis: {
      driver: 'redis',
      url: 'redis://localhost:6379',
    },
  },
  routeRules: {
    '/blog/**': {
      swr: 60 * 60,
      cache: {
        base: 'redis',
      },
    },
  },
})

Options

cachedEventHandlercachedFunction 函数接受以下选项:

  • name: Handler name.
    • Type: String
    • 默认:如果未提供,则从函数名称猜测,否则回退到 _ 。
  • group: 缓存名称的一部分。 用于组织缓存存储。
    • Type: String
    • 默认:'nitro/handlers' 用于处理程序,'nitro/functions' 用于函数。
  • getKey: 接受与函数相同的参数并返回缓存键 (String) 的函数。
    • Type: Function
    • 默认:如果未提供,将使用内置哈希函数。
  • integrity: 更改时使缓存无效的值。
    • Type: String
    • 默认:从函数代码计算,在开发中用于在函数代码更改时使缓存失效。
  • maxAge: 缓存有效的最长期限(以秒为单位)。
    • Type: Number
    • 默认:1(第二个)。
  • staleMaxAge: 陈旧缓存有效的最长期限(以秒为单位)。 如果设置为“-1”,旧值仍将发送到客户端,同时在后台更新缓存。
    • Type: Number
    • 默认:0(禁用)。
  • swr: Enable stale-while-revalidate behavior.
    • 默认:真实
  • base: 用于缓存的存储安装点的名称。
    • 默认:缓存
  • shouldInvalidateCache: 返回“布尔值”以使当前缓存无效并创建新缓存的函数。
    • Type: Function
  • shouldBypassCache: 返回布尔值以绕过当前缓存而不会使现有条目无效的函数。
    • Type: Function