---
title: Cloudflare Workers与边缘缓存策略实践
keywords:
- Cloudflare Workers
- 边缘缓存
- KV
- Cache API
- wrangler
- Cache-Control
description: 使用Workers与边缘缓存策略降低源站压力与延迟,通过Cache API与cf选项实现可验证的TTL与命中率提升。
date: 2025-11-26
categories:
- 文章资讯
- 技术教程
---
概述
- 目标:在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验证命中率改进。

发表评论 取消回复