服务器

缓存

如何在 NuxtHub 中使用缓存存储。

NuxtHub 缓存使用 Cloudflare Workers KV 来缓存您的服务器路由响应或函数,使用 Nitro 的 cachedEventHandlercachedFunction.

入门

通过在您的 NuxtHub 项目的 nuxt.config.ts 文件中将 cache 属性添加到 hub 对象中,启用缓存存储。

nuxt.config.ts
export default defineNuxtConfig({
  hub: {
    cache: true
  }
})

部署项目后,您可以在 NuxtHub 管理员 中访问缓存存储。您可以在项目页面中的 缓存 部分管理您的缓存条目。

事件处理程序缓存

使用 cachedEventHandler 函数,您可以缓存服务器路由的响应。此函数将服务器路由的响应缓存到 NuxtHub 缓存存储中。

server/api/cached-route.ts
import type { H3Event } from 'h3'

export default cachedEventHandler((event) => {
  return {
    success: true,
    date: new Date().toISOString()
  }
}, {
  maxAge: 60 * 60, // 1 hour
  getKey: (event: H3Event) => event.node.req.url
})

上面的示例将 /api/cached-route 路由的响应缓存 1 小时。 getKey 函数用于生成缓存条目的键。

阅读更多关于 Nitro 缓存选项 的信息。

函数缓存

使用 cachedFunction 函数,您可以缓存函数。这对于缓存不是事件处理程序而是其一部分的函数的结果并将其在多个处理程序中重用非常有用。

server/utils/cached-function.ts
import type { H3Event } from 'h3'

export const getRepoStarCached = defineCachedFunction(async (event: H3Event, repo: string) => {
  const data: any = await $fetch(`https://api.github.com/repos/${repo}`)

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

上面的示例将 getRepoStarCached 函数的结果缓存 1 小时。

需要注意的是, event 参数始终应该是缓存函数的第一个参数。Nitro 利用 event.waitUntil 在更新缓存的同时将实例保持活动状态,同时将响应发送到客户端。
在 Nitro 文档中阅读更多关于此的信息.