ARTICLE DETAIL

资讯详情

深耕编程入门与网站建设的一线实战洞察。

Cloudflare Cache Reserve API 实战指南:Workers 集成、缓存清理与监控分析

Cloudflare Cache Reserve API 实战指南:Workers 集成、缓存清理与监控分析 Cloudflare Cache Reserve API 实战指南Workers 集成、缓存清理与监控分析【免费下载链接】skillsSkills Catalog for Codex项目地址: https://gitcode.com/GitHub_Trending/skills4/skills导读Cache Reserve 是 Cloudflare 基于 R2 构建的持久化缓存层默认保留内容 30 天以上用于提升缓存命中率、降低源站出口流量费用并屏蔽针对长尾内容的重复回源请求。本文以 Cache Reserve API 参考文档 为主线深入讲解它与 Workers 的集成边界为什么cache.put()不兼容 Cache Reserve、三种缓存清理方式按 URL、按 Tag/Host/Prefix、全量清空的差异、Logpush 与 GraphQL 分析查询以及精确到每 GB、每百万次操作的定价模型并辅以仓库内 configuration.md、gotchas.md 等文档交叉印证。读完本文你将能够正确地在 Workers 中配合 Cache Reserve 编程、用 REST API 管理缓存生命周期并用可复制的查询脚本量化它的命中率与成本。Cache Reserve 的本质Zone 级配置而非按请求的 API理解 Cache Reserve API 的第一个关键前提是Cache Reserve 是一个 Zone区域级别的配置而不是一个按请求粒度调用的 API。当你在该 Zone 上启用它之后它会自动生效无需在每次请求中显式调用任何接口。当 Zone 上的缓存未命中时内容会同时写入 Cache Reserve 与边缘缓存当内容从边缘缓存被淘汰后它仍保留在 Cache Reserve 中当下一次请求在边缘缓存未命中、但在 Cache Reserve 命中时内容会被回填到边缘缓存资产在 Cache Reserve 中的保留期为自上次访问起 30 天可通过 TTL 配置。正是这种自动、Zone 级、无感知的设计决定了它与 Workers 缓存 API 之间的关系——这也是 api.md 开头用一个醒目的警示框强调的核心要点。Workers 集成标准 fetch 是唯一正确姿势关键警告Workers Cache API ≠ Cache Reserve在 Workers 中最容易犯的错误是把caches.default与 Cache Reserve 混为一谈。两者的区别如下维度Workers Cache APIcaches.default/cache.put()Cache Reserve作用层级请求级、代码控制的边缘缓存Zone 级自动配置调用方式显式cache.match()/cache.put()无需代码自动工作与标准fetch()不相关兼容随标准 fetch 自动生效是否可选择性写入可以按请求写入不可以无法从 Workers 选择性写入适用场景自定义缓存命名空间全局持久化缓存层cache.put()不兼容Cache Reserve 与 Tiered Cache。在 Workers 中调用cache.put()只会写入边缘缓存而绕过 Cache Reserve这会导致你的持久化缓存层形同虚设。标准 fetch推荐// Cache Reserve works automatically via standard fetch export default { async fetch(request: Request, env: Env): PromiseResponse { // Standard fetch uses Cache Reserve automatically return await fetch(request); } };这是与 Cache Reserve 配合的唯一推荐方式只要 Zone 级开启了 Cache Reserve标准fetch()就会自动走完整的缓存层级下层级缓存 → 上层级缓存 → Cache Reserve → 源站。在仓库的 workers/api.md 中可以找到标准的 Cache API 写法但需要注意那部分代码展示的是边缘缓存的使用方式并不代表它会写入 Cache Reserve。Cache API 的使用边界正确与错误的示范// ❌ WRONG: cache.put() bypasses Cache Reserve const cache caches.default; let response await cache.match(request); if (!response) { response await fetch(request); await cache.put(request, response.clone()); // Bypasses Cache Reserve! } // ✅ CORRECT: Use standard fetch for Cache Reserve compatibility return await fetch(request); // ✅ CORRECT: Use Cache API only for custom cache namespaces const customCache await caches.open(my-custom-cache); let response await customCache.match(request); if (!response) { response await fetch(request); await customCache.put(request, response.clone()); // Custom cache OK }需要澄清的实践边界错误做法用cache.put()手动写入caches.default这会绕过 Cache Reserve也让 Tiered Cache 失效正确做法 A直接return await fetch(request)把缓存决策完全交给 Zone 级配置正确做法 B如果确实需要 Workers 级缓存控制请使用caches.open(my-custom-cache)打开自定义缓存命名空间。自定义命名空间不受 Cache Reserve 影响cache.put()在其中是合法且有效的。补充一点来自 patterns.md 的实现细节Workers 无法直接控制 Cache Reserve 的写入但可以通过修改响应头来让资产满足入选条件例如设置Cache-Control: public, max-age36000、删除Set-Cookie、补全Content-Length。这属于间接提升入选率而不是按请求写 Cache Reserve。缓存清理与管理Purge 的三种姿势Cache Reserve 的清理通过 Cloudflare REST API 完成统一端点格式为https://api.cloudflare.com/client/v4/zones/{zoneId}/purge_cache按 URL 清理即时生效按 URL 清理会立即从 Cache Reserve 和边缘缓存中移除资产适合发布新版本、修复错误图片等场景// Purge specific URL from Cache Reserve immediately const purgeCacheReserveByURL async ( zoneId: string, apiToken: string, urls: string[] ) { const response await fetch( https://api.cloudflare.com/client/v4/zones/${zoneId}/purge_cache, { method: POST, headers: { Authorization: Bearer ${apiToken}, Content-Type: application/json, }, body: JSON.stringify({ files: urls }) } ); return await response.json(); }; // Example usage await purgeCacheReserveByURL(zone123, token456, [ https://example.com/image.jpg, https://example.com/video.mp4 ]);按 Tag / Host / Prefix 清理触发重新验证按标签、主机或前缀清理只触发重新验证revalidation不会立即从存储中移除资产——这意味着存储费用会继续产生直到 TTL 自然到期// Purge by cache tag - forces revalidation, not immediate removal await fetch( https://api.cloudflare.com/client/v4/zones/${zoneId}/purge_cache, { method: POST, headers: { Authorization: Bearer ${apiToken}, Content-Type: application/json }, body: JSON.stringify({ tags: [tag1, tag2] }) } );Purge 行为差异总结按 URL立即从 Cache Reserve 边缘缓存移除按 Tag / Host / Prefix仅触发重新验证资产仍留在存储中费用继续产生。这一点在 gotchas.md 的Purge Not Working as Expected一节有明确佐证如果预期是彻底移除请使用按 URL 清理或先关闭 Cache Reserve 再全量清空。全量清空 Cache Reserve 数据先关闭再清空// Requires Cache Reserve OFF first await fetch( https://api.cloudflare.com/client/v4/zones/${zoneId}/cache/cache_reserve_clear, { method: POST, headers: { Authorization: Bearer ${apiToken} } } ); // Check status: GET same endpoint returns { state: In-progress | Completed }完整流程禁用 Cache Reserve → 调用清空端点 → 等待最长 24 小时传播 → 重新启用。仓库中的 gotchas.md 补充了两个关键细节在 Cache Reserve 仍处于启用状态时调用清空接口会失败必须先关闭关闭后建议等待约 5 秒让配置传播再进行清空清空操作完全生效最长需要 24 小时期间可以通过对同一端点发送 GET 请求查询状态返回In-progress或Completed。监控与分析Dashboard、Logpush 与 GraphQLDashboard 指标登录 Cloudflare 控制台进入Caching Cache Reserve页面可以查看Egress SavingsCache Reserve 服务的总字节数以及相对源站出口流量节省的成本Requests ServedCache Reserve 命中与未命中的细分Storage Used当前存储在 Cache Reserve 中的 GB 数按月计费OperationsClass A写入与 Class B读取操作计数Cost Tracking基于当前用量估算的月度费用。Logpush 集成按 CacheReserveUsed 字段过滤Logpush 提供的CacheReserveUsed布尔值字段可以直接用来区分 Cache Reserve 命中与未命中请求。以下 SQL 查询可在 Cloudflare AnalyticsGraphQL Analytics API中运行// Logpush field: CacheReserveUsed (boolean) - filter for Cache Reserve hits // Query Cache Reserve hits in analytics const logpushQuery SELECT ClientRequestHost, COUNT(*) as requests, SUM(EdgeResponseBytes) as bytes_served, COUNT(CASE WHEN CacheReserveUsed true THEN 1 END) as cache_reserve_hits, COUNT(CASE WHEN CacheReserveUsed false THEN 1 END) as cache_reserve_misses FROM http_requests WHERE Timestamp NOW() - INTERVAL 24 hours GROUP BY ClientRequestHost ORDER BY requests DESC ; // Filter only Cache Reserve hits const crHitsQuery SELECT ClientRequestHost, COUNT(*) as requests, SUM(EdgeResponseBytes) as bytes FROM http_requests WHERE CacheReserveUsed true AND Timestamp NOW() - INTERVAL 7 days GROUP BY ClientRequestHost ORDER BY bytes DESC ;这两条查询的实战价值第一条按主机名聚合 24 小时内的请求量、服务字节数与命中/未命中计数用于快速定位哪些域名的 Cache Reserve 利用率最高第二条只看 7 天内CacheReserveUsed true的请求并按服务字节排序用于找出缓存收益最大的资产路径。排查提示来自 gotchas.md 的故障排查流程第 9 步当资产疑似未进入 Cache Reserve 时可以结合 Logpush 的CacheReserveUsed字段确认资产是否真正命中过 Cache Reserve并通过响应头cf-cache-status验证首次请求后应为HIT。GraphQL Analytics 查询如果偏好 GraphQL可以使用以下查询获取按天聚合的缓存字节数、缓存请求数等指标query CacheReserveAnalytics($zoneTag: string, $since: string, $until: string) { viewer { zones(filter: { zoneTag: $zoneTag }) { httpRequests1dGroups( filter: { datetime_geq: $since, datetime_leq: $until } limit: 1000 ) { dimensions { date } sum { cachedBytes cachedRequests bytes requests } } } } }httpRequests1dGroups返回按天分组的聚合结果sum块中的四个字段分别对应缓存字节数、缓存请求数、总字节数与总请求数配合datetime_geq/datetime_leq可以灵活圈定分析窗口。定价模型存储 操作费Cache Reserve 采用按量计费具体单价如下// Storage: $0.015/GB-month | Class A (writes): $4.50/M | Class B (reads): $0.36/M // Cache miss: 1A 1B | Cache hit: 1B | Assets 1GB: proportionally more ops拆解要点存储每 GB 每月 0.015 美元Class A写入每百万次 4.50 美元Class B读取每百万次 0.36 美元缓存未命中1 次 Class A 1 次 Class B回源写入 读取各一次缓存命中仅 1 次 Class B纯读取超过 1GB 的资产按比例产生更多操作次数。patterns.md 中提供了一个完整的成本估算函数可在选型阶段对比Cache Reserve 费用 vs 源站出口费用的净节省interface CacheReserveEstimate { avgAssetSizeGB: number; uniqueAssets: number; monthlyReads: number; monthlyWrites: number; originEgressCostPerGB: number; // e.g., AWS: $0.09/GB } function estimateMonthlyCost(input: CacheReserveEstimate) { // Cache Reserve pricing const storageCostPerGBMonth 0.015; const classAPerMillion 4.50; // writes const classBPerMillion 0.36; // reads // Calculate Cache Reserve costs const totalStorageGB input.avgAssetSizeGB * input.uniqueAssets; const storageCost totalStorageGB * storageCostPerGBMonth; const writeCost (input.monthlyWrites / 1_000_000) * classAPerMillion; const readCost (input.monthlyReads / 1_000_000) * classBPerMillion; const cacheReserveCost storageCost writeCost readCost; // Calculate origin egress cost (what youd pay without Cache Reserve) const totalTrafficGB (input.monthlyReads * input.avgAssetSizeGB); const originEgressCost totalTrafficGB * input.originEgressCostPerGB; // Savings calculation const savings originEgressCost - cacheReserveCost; const savingsPercent ((savings / originEgressCost) * 100).toFixed(1); return { cacheReserveCost: $${cacheReserveCost.toFixed(2)}, originEgressCost: $${originEgressCost.toFixed(2)}, monthlySavings: $${savings.toFixed(2)}, savingsPercent: ${savingsPercent}%, breakdown: { storage: $${storageCost.toFixed(2)}, writes: $${writeCost.toFixed(2)}, reads: $${readCost.toFixed(2)}, } }; }成本优化提示稳定内容建议设置 24 小时以上的 TTL配合 Tiered Cache 减少直接落到 Cache Reserve 的未命中或使用 stale-while-revalidate 降低 Class A 写入成本同时注意 Cache Reserve 从源站抓取的是未压缩内容、对访客自动压缩若源站按带宽计费需将未压缩传输成本计入对比。常见误用与避坑清单综合 gotchas.md 与本 API 文档以下是在编程集成中最容易踩的坑误用场景原因正确做法在 Workers 中用cache.put()写入默认缓存以为能写入 Cache Reserve改用标准fetch()Cache Reserve 自动生效用cache.put()写入自定义命名空间后担心绕过 Cache Reserve混淆两种缓存自定义命名空间caches.open本就独立可用按 Tag 清理却期待资产立即消失按 Tag 只触发 revalidation彻底移除请用按 URL 清理或先关闭再全量清空未关闭 Cache Reserve 就调用清空接口接口要求在禁用状态下调用先关闭、等约 5 秒传播、再清空、等待最多 24 小时依赖cf-cache-status判断却忽略CacheReserveUsed指标不完整用 Logpush 的CacheReserveUsed字段精确统计命中用 Workers 处理视频 seekingRange 请求Cache Reserve 不支持 HTTP 206Range 请求会绕过 Cache Reserve仅走边缘缓存或直接使用 R2延伸阅读本主题在仓库中还有三份配套文档建议按需继续深入Cache Reserve 概览README核心概念、缓存层级、资产入选条件与适用场景判断Cache Reserve 配置configuration.mdDashboard 开启、REST API、TypeScript/Python SDK、Terraform/Pulumi 与 Cache Rules 集成Cache Reserve 最佳实践patterns.md多层缓存架构、Cache Rules 精细控制、成本估算Cache Reserve 常见问题gotchas.md9 步故障排查流程与完整 Limits 表Workers API 参考Workers 中 Cache API、fetch 等运行时能力的基础用法。【免费下载链接】skillsSkills Catalog for Codex项目地址: https://gitcode.com/GitHub_Trending/skills4/skills创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表