0Pricing
Edge Computing with Cloudflare Workers & Deno · 课时

缓存策略

使用 Cloudflare 的 CDN 和 Workers Cache API 实现高效的缓存机制,降低延迟

缓存策略 是 CoddyKit 上的免费 Edge Computing with Cloudflare Workers & Deno 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Edge Computing with Cloudflare Workers & Deno 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Edge Computing with Cloudflare Workers & Deno 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

What is Caching?

Imagine you need to grab a book. If it's on your desk, it's super fast! If it's at the local library, it's still quick. But if you have to order it from a distant warehouse, it takes much longer.

Caching works similarly. It's the process of storing copies of frequently accessed data closer to where it's needed, speeding up future requests.

Why Cache at the Edge?

In edge computing, 'closer' means at the edge of the network, near your users. Caching at the edge offers several key benefits:

  • Reduced Latency: Content reaches users faster.
  • Reduced Origin Load: Your main servers handle fewer requests.
  • Improved User Experience: Websites and applications feel snappier.

Cloudflare CDN Caching

Cloudflare's Content Delivery Network (CDN) is your first line of defense for caching. It automatically stores static assets (like images, CSS files, and JavaScript bundles) at its global network of edge locations.

When a user requests one of these assets, Cloudflare serves it from the nearest edge server, not your origin server.

HTTP Cache-Control Headers

You can tell CDNs and browsers how to cache your content using HTTP Cache-Control headers. These headers are sent with your server's response.

  • max-age=X: Resource is fresh for X seconds.
  • s-maxage=Y: Specifically for shared caches (CDNs), overrides max-age.
  • no-cache: Must revalidate with origin before serving cached content.
  • no-store: Never cache this content.

Workers Cache API Intro

While Cloudflare's CDN handles static assets, what about dynamic content or API responses? That's where the Cloudflare Workers Cache API comes in.

This powerful API allows your Worker to programmatically store and retrieve any HTTP Response object in Cloudflare's global cache, giving you fine-grained control.

Basic Cache API Flow

The Workers Cache API uses a simple key-value pattern:

  • Key: An HTTP Request object (or a URL string).
  • Value: An HTTP Response object.

You use cache.put(request, response) to store and cache.match(request) to retrieve.

Storing with cache.put()

Let's write a Worker that fetches a resource from an origin and then stores a copy of its response in the cache using cache.put(). This makes it available for future requests.

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event));
});

async function handleRequest(event) {
  const request = event.request;
  const cacheKey = new Request(request.url, request); // Key for cache
  const cache = caches.default; // Get default cache storage

  // Fetch from the origin server
  const response = await fetch(request);

  // Store a clone of the response in cache
  // event.waitUntil ensures caching happens in background
  event.waitUntil(cache.put(cacheKey, response.clone()));

  return response; // Return the original response
}

Retrieving with cache.match()

Now, let's modify the Worker to first check if the requested resource is in the cache using cache.match(). If found, we return the cached version immediately. Otherwise, we fetch from the origin and then cache it.

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event));
});

async function handleRequest(event) {
  const request = event.request;
  const cacheKey = new Request(request.url, request);
  const cache = caches.default;

  // Try to find the response in cache
  let response = await cache.match(cacheKey);

  if (response) {
    // Cache hit! Return cached response
    return response;
  }

  // Cache miss. Fetch from origin
  response = await fetch(request);

  // Store the new response in cache for next time
  event.waitUntil(cache.put(cacheKey, response.clone()));

  return response;
}

Cache Invalidation & Best Practices

Effective caching requires managing stale data. Here are some tips:

  • Purging: Use the Cloudflare dashboard or API to invalidate specific URLs.
  • Vary Header: Use the Vary HTTP header (e.g., Vary: Accept-Encoding) to cache different versions based on request headers.
  • Time-based Expiry: Set appropriate Cache-Control headers or options in cache.put() to automatically expire cached items.

Test Your Knowledge

The Cloudflare Workers Cache API allows you to programmatically control caching. Which method is used to store a response in the cache?

Recap: Caching Strategies

In this lesson, we explored powerful caching strategies to optimize performance at the edge:

  • Cloudflare's CDN automatically caches static assets.
  • HTTP Cache-Control headers allow you to define caching behavior.
  • The Workers Cache API provides programmatic control for caching dynamic content.
  • Proper cache invalidation and management are crucial for fresh data.

Mastering caching is key to building fast, efficient edge applications!

常见问题解答

「缓存策略」课时是免费的吗?

是的 — 「缓存策略」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Edge Computing with Cloudflare Workers & Deno 课程的其余内容,请升级到 CoddyKit PRO。 Edge Computing with Cloudflare Workers & Deno 课程共包含 4 节课。

「缓存策略」这节课中我会学到什么?

使用 Cloudflare 的 CDN 和 Workers Cache API 实现高效的缓存机制,降低延迟 你通过在浏览器中直接运行的动手代码来练习 Edge Computing with Cloudflare Workers & Deno,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Edge Computing with Cloudflare Workers & Deno 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Edge Computing with Cloudflare Workers & Deno 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「缓存策略」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Edge Computing with Cloudflare Workers & Deno 课中编写并运行代码吗?

能。每节 Edge Computing with Cloudflare Workers & Deno 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 缓存策略
  2. 冷启动与预热
  3. 监控与日志记录
  4. 打包体积与代码优化
← 返回 Edge Computing with Cloudflare Workers & Deno