使用 Cache API 加速你的 Worker(5 行代码)

发布: (2025年12月29日 GMT+8 18:05)
2 min read
原文: Dev.to

Source: Dev.to

使用 Cache API 只需 5 行代码

export default {
  async fetch(request) {
    const cache = caches.default;
    let response = await cache.match(request);
    if (!response) {
      response = await fetch(request);
      response = new Response(response.body, response);
      response.headers.set('Cache-Control', 'max-age=3600');
      await cache.put(request, response.clone());
    }
    return response;
  }
};

性能影响

  • 缓存前:每个请求都会访问源站(延迟 200‑500 ms,CPU 使用率高)。
  • 缓存后:缓存命中的请求在 <10 ms 内返回,命中率通常在 70‑90 % 左右,CPU 使用极低。
  • 我的 API 示例
    • P50 延迟:450 ms → 15 ms
    • P95 延迟:800 ms → 25 ms
    • 缓存命中率:85 %

最佳实践

  • 仅缓存 GET 请求。
  • 设置合适的 TTL(例如 max-age=3600 表示 1 小时)——避免永久缓存。
  • 为不同的变体(查询参数、请求头等)使用不同的缓存键。
  • 当底层数据变化时,及时失效或更新缓存。

其他资源

想了解更多性能模式,请参阅完整指南:https://appybot.gumroad.com/l/oatoe

Back to Blog

相关文章

阅读更多 »