← Cloudflare Workers KV / kv / examples
Кэширование данных с помощью Workers KV
Workers KV можно использовать как постоянный единый глобальный кэш, доступный из Cloudflare Workers, чтобы ускорить работу приложения. Данные, кэшированные в Workers KV, доступны также из всех остальных дата-центров Cloudflare и хранятся вплоть до истечения срока действия или удаления.
После получения данных из внешних ресурсов в приложении Workers вы можете записать эти данные в Workers KV. При последующих запросах к Worker (в том же регионе или в других регионах) вы можете считывать закэшированные данные из Workers KV вместо повторного обращения к внешнему API. Это повышает производительность и отказоустойчивость приложения Worker и снижает нагрузку на внешние ресурсы.
Этот пример показывает, как кешировать данные в Workers KV и читать кешированные данные из Workers KV в приложении Worker.
Кэширование данных в Workers KV из приложения Worker
В следующем index.ts файле Worker получает данные с внешнего сервера и кэширует ответ в Workers KV. Если данные уже закэшированы в Workers KV, Worker считывает их из Workers KV, не обращаясь к внешнему API.
interface Env {
CACHE_KV: KVNamespace;
}
export default {
async fetch(request, env, ctx): Promise<Response> {
const EXPIRATION_TTL = 30; // Cache expiration in seconds
const url = 'https://example.com';
const cacheKey = "cache-json-example";
// Try to get data from KV cache first
let data = await env.CACHE_KV.get(cacheKey, { type: 'json' });
let fromCache = true;
// If data is not in cache, fetch it from example.com
if (!data) {
console.log('Cache miss. Fetching fresh data from example.com');
fromCache = false;
// In this example, we are fetching HTML content but it can also be API responses or any other data
const response = await fetch(url);
const htmlData = await response.text();
// In this example, we are converting HTML to JSON to demonstrate caching JSON data with Workers KV
// You could cache any type of data, or even cache the HTML data directly
data = helperConvertToJSON(htmlData);
// The expirationTtl option is used to set the expiration time for the cache entry (in seconds), otherwise it will be stored indefinitely
await env.CACHE_KV.put(cacheKey, JSON.stringify(data), { expirationTtl: EXPIRATION_TTL });
}
// Return the appropriate response format
return new Response(JSON.stringify({
data,
fromCache
}), {
headers: { 'Content-Type': 'application/json' }
});
}
} satisfies ExportedHandler<Env>;
// Helper function to convert HTML to JSON
function helperConvertToJSON(html: string) {
// Parse HTML and extract relevant data
const title = helperExtractTitle(html);
const content = helperExtractContent(html);
const lastUpdated = new Date().toISOString();
return { title, content, lastUpdated };
}
// Helper function to extract title from HTML
function helperExtractTitle(html: string) {
const titleMatch = html.match(/<title>(.\*?)<\/title>/i);
return titleMatch ? titleMatch[1] : 'No title found';
}
// Helper function to extract content from HTML
function helperExtractContent(html: string) {
const bodyMatch = html.match(/<body>(.\*?)<\/body>/is);
if (!bodyMatch) return 'No content found';
// Strip HTML tags for a simple text representation
const textContent = bodyMatch[1].replace(/<[^>]*>/g, ' ')
.replace(/\s+/g, ' ')
.trim();
return textContent;
}{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "<ENTER_WORKER_NAME>",
"main": "src/index.ts",
"compatibility_date": "2025-03-03",
"observability": {
"enabled": true
},
"kv_namespaces": [
{
"binding": "CACHE_KV",
"id": "<YOUR_BINDING_ID>"
}
]
}Этот фрагмент кода показывает, как читать и обновлять кешированные данные в Workers KV из вашего Worker. Если данных нет в кеше Workers KV, Worker получает их с внешнего сервера и кеширует в Workers KV.
В этом примере мы преобразуем HTML в JSON, чтобы показать, как кешировать данные JSON с помощью Workers KV, но в Workers KV можно кешировать данные любого типа. Например, можно кешировать ответы API, содержимое HTML или любые другие данные, которые нужно сохранять между запросами.