Appearance
缓存中间件
¥Cache Middleware
Cache 中间件使用 Web 标准的 缓存 API。
¥The Cache middleware uses the Web Standards' Cache API.
Cache 中间件目前支持使用自定义域的 Cloudflare Workers 项目和使用 Deno 1.26+ 的 Deno 项目。也可用于 Deno Deploy。
¥The Cache middleware currently supports Cloudflare Workers projects using custom domains and Deno projects using Deno 1.26+. Also available with Deno Deploy.
Cloudflare Workers 尊重 Cache-Control
标头并返回缓存的响应。有关详细信息,请参阅 Cloudflare 文档上的缓存。Deno 不尊重标头,因此如果你需要更新缓存,则需要实现自己的机制。
¥Cloudflare Workers respects the Cache-Control
header and return cached responses. For details, refer to Cache on Cloudflare Docs. Deno does not respect headers, so if you need to update the cache, you will need to implement your own mechanism.
有关每个平台的说明,请参阅下面的 用法。
¥See Usage below for instructions on each platform.
导入
¥Import
ts
import { Hono } from 'hono'
import { cache } from 'hono/cache'
用法
¥Usage
ts
app.get(
'*',
cache({
cacheName: 'my-app',
cacheControl: 'max-age=3600',
})
)
ts
// Must use `wait: true` for the Deno runtime
app.get(
'*',
cache({
cacheName: 'my-app',
cacheControl: 'max-age=3600',
wait: true,
})
)
选项
¥Options
required cacheName:string
| (c: Context) => string
| Promise<string>
缓存的名称。可用于存储具有不同标识符的多个缓存。
¥The name of the cache. Can be used to store multiple caches with different identifiers.
optional wait:boolean
一个布尔值,表示 Hono 是否应等待 cache.put
函数的 Promise 解析后再继续请求。对于 Deno 环境,必须为真。默认为 false
。
¥A boolean indicating if Hono should wait for the Promise of the cache.put
function to resolve before continuing with the request. Required to be true for the Deno environment. The default is false
.
optional cacheControl:string
Cache-Control
标头的指令字符串。有关更多信息,请参阅 MDN 文档。未提供此选项时,不会将 Cache-Control
标头添加到请求中。
¥A string of directives for the Cache-Control
header. See the MDN docs for more information. When this option is not provided, no Cache-Control
header is added to requests.
optional evolve:string
| string[]
在响应中设置 Vary
标头。如果原始响应标头已包含 Vary
标头,则合并值,删除任何重复项。将其设置为 *
将导致错误。有关 Vary 标头及其对缓存策略的影响的更多详细信息,请参阅 MDN 文档。
¥Sets the Vary
header in the response. If the original response header already contains a Vary
header, the values are merged, removing any duplicates. Setting this to *
will result in an error. For more details on the Vary header and its implications for caching strategies, refer to the MDN docs.
optional keyGenerator:(c: Context) => string | Promise<string>
为 cacheName
存储中的每个请求生成密钥。这可用于根据请求参数或上下文参数缓存数据。默认为 c.req.url
。
¥Generates keys for every request in the cacheName
store. This can be used to cache data based on request parameters or context parameters. The default is c.req.url
.