Strategie buforowania
Zaimplementuj skuteczne mechanizmy buforowania z użyciem CDN Cloudflare i Workers Cache API, aby zmniejszyć opóźnienia
Strategie buforowania to bezpłatna lekcja Edge Computing with Cloudflare Workers & Deno na CoddyKit. To lekcja 1 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Edge Computing with Cloudflare Workers & Deno, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Edge Computing with Cloudflare Workers & Deno zawiera 4 lekcji w sumie.
Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.
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 forXseconds.s-maxage=Y: Specifically for shared caches (CDNs), overridesmax-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 Requestobject (or a URL string). - Value: An
HTTP Responseobject.
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
VaryHTTP header (e.g.,Vary: Accept-Encoding) to cache different versions based on request headers. - Time-based Expiry: Set appropriate
Cache-Controlheaders or options incache.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-Controlheaders 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!
Ucz się Edge Computing with Cloudflare Workers & Deno dzięki korepetycjom AI — za darmo
Pisz i uruchamiaj kod w przeglądarce, otrzymuj natychmiastową pomoc od korepetytora AI dostępnego 24/7 i kontynuuj naukę w sieci lub w aplikacji.
- Kursy
- 12
- Lekcje
- 47
Często zadawane pytania
Czy lekcja „Strategie buforowania” jest bezpłatna?
Tak — pełny tekst „Strategie buforowania” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Edge Computing with Cloudflare Workers & Deno, przejdź na CoddyKit PRO. Kurs Edge Computing with Cloudflare Workers & Deno zawiera 4 lekcji w sumie.
Co nauczysz się w „Strategie buforowania”?
Zaimplementuj skuteczne mechanizmy buforowania z użyciem CDN Cloudflare i Workers Cache API, aby zmniejszyć opóźnienia Ćwiczysz Edge Computing with Cloudflare Workers & Deno z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.
Czy potrzebuję doświadczenia, aby zacząć Edge Computing with Cloudflare Workers & Deno?
Nie wymagamy żadnego doświadczenia. Edge Computing with Cloudflare Workers & Deno w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 1 z 4.
Ile czasu zajmuje lekcja „Strategie buforowania”?
Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.
Czy mogę pisać i uruchamiać kod w tej lekcji Edge Computing with Cloudflare Workers & Deno?
Tak. Każda lekcja Edge Computing with Cloudflare Workers & Deno zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.
Wszystkie lekcje w tym kursie
- Strategie buforowania
- Cold starty i rozgrzewanie
- Monitorowanie i rejestrowanie
- Rozmiar bundla i optymalizacja kodu