概述目标:在Cloudflare边缘以Workers实现就近缓存与计算,减少回源,提高全球延迟表现与可用性。能力:`caches.default`、`fetch`的`cf`缓存选项、KV存储作为元数据或预渲染缓存。核心与实战Worker示例(优先命中边缘缓存,未命中则回源并写入缓存):export default {
async fetch(request, env, ctx) {
const cache = caches.default
const cacheKey = new Request(new URL(request.url), request)
let response = await cache.match(cacheKey)
if (!response) {
response = await fetch(request, {
cf: { cacheTtl: 300, cacheEverything: true }
})
// 设置响应头以便浏览器端也缓存
response = new Response(response.body, response)
response.headers.set('Cache-Control', 'public, max-age=300')
ctx.waitUntil(cache.put(cacheKey, response.clone()))
}
return response
}
}
KV作为预渲染/配置数据:export default {
async fetch(request, env) {
const path = new URL(request.url).pathname
const cachedHtml = await env.HTML_KV.get(path)
if (cachedHtml) {
return new Response(cachedHtml, { headers: { 'Content-Type': 'text/html', 'Cache-Control': 'public, max-age=600' } })
}
// 回源生成并写入KV
const html = `<html><body><h1>${path}</h1></body></html>`
await env.HTML_KV.put(path, html, { expirationTtl: 600 })
return new Response(html, { headers: { 'Content-Type': 'text/html' } })
}
}
`wrangler.toml`配置示例:name = "edge-cache"
main = "src/index.js"
compatibility_date = "2025-11-26"
[env.production]
route = "example.com/*"
workers_dev = false
[[kv_namespaces]]
binding = "HTML_KV"
id = "<your-kv-id>"
示例指定缓存键的标准化(去除查询参数):export default {
async fetch(request) {
const url = new URL(request.url)
url.search = ''
const key = new Request(url.toString(), request)
const hit = await caches.default.match(key)
if (hit) return hit
const resp = await fetch(url.toString(), { cf: { cacheTtl: 120 } })
await caches.default.put(key, resp.clone())
return resp
}
}
强制跳过缓存用于调试:fetch(request, { cf: { cacheTtl: 0, cacheEverything: false, cacheKey: undefined } })
验证与监控命中率与带宽:Cloudflare Analytics中观察`Cache Hit/Miss`、`Bandwidth Saved`。回源量与状态码分布:监控`Origin Requests`与4xx/5xx占比,确保缓存配置未导致错误传播。头部校验:浏览器与边缘响应头检查`CF-Cache-Status: HIT`/`MISS`与`Cache-Control`的TTL是否符合预期。常见误区未设置`cacheEverything`导致仅静态资源被缓存;动态页面需显式开启或通过Workers设置响应头与Cache API。缓存键混乱(含多余查询参数)导致命中率低;应规范化URL并自定义`cacheKey`。忽视KV一致性与写入延迟,将KV当强一致数据库使用;KV适合作为缓存/配置,不适合事务场景。结语结合Workers的计算与边缘缓存策略,可显著降低源站负载与全球延迟,并以Analytics验证命中率改进。

发表评论 取消回复