Workers KV로 데이터 캐시하기 (Cache data with Workers KV)
Workers KV를 캐시로 사용해서 애플리케이션 성능을 개선하는 예시 문서예요. 외부 API 응답을 KV에 캐시하고 재사용하는 방법을 보여줘요.
출처: 문서
본문
Cache data with Workers KV
Workers KV에서 데이터나 API 응답을 캐시해 애플리케이션 성능을 개선하세요.
Workers KV는 Cloudflare Workers에서 접근 가능한 영구적이고 단일한 전 세계 캐시로 사용할 수 있어요. 그러면 애플리케이션 속도를 높일 수 있어요. Workers KV에 캐시된 데이터는 다른 모든 Cloudflare 위치에서도 접근할 수 있고, 만료되거나 삭제될 때까지 유지돼요.
Workers 애플리케이션에서 외부 리소스에서 데이터를 가져온 후 그 데이터를 Workers KV에 쓸 수 있어요. 이후의 Worker 요청(같은 지역 또는 다른 지역)에서는 외부 API를 호출하는 대신 Workers KV에서 캐시된 데이터를 읽을 수 있어요. 이렇게 하면 Worker 애플리케이션의 성능과 복원력이 개선되고 외부 리소스에 대한 부하가 줄어들어요.
이 예시는 Worker 애플리케이션에서 Workers KV에 데이터를 캐시하고 Workers KV에서 캐시된 데이터를 읽는 방법을 보여줘요.
Worker 애플리케이션에서 Workers KV에 데이터 캐시하기
다음 index.ts 파일에서 Worker는 외부 서버에서 데이터를 가져와 응답을 Workers KV에 캐시해요. 데이터가 이미 Workers KV에 캐시되어 있다면 Worker는 외부 API를 호출하는 대신 Workers KV에서 캐시된 데이터를 읽어요.
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>"
}
]
}
이 코드 스니펫은 Worker에서 Workers KV의 캐시된 데이터를 읽고 업데이트하는 방법을 보여줘요. 데이터가 Workers KV 캐시에 없다면 Worker는 외부 서버에서 데이터를 가져와 Workers KV에 캐시해요.
이 예시에서는 Workers KV로 JSON 데이터를 캐시하는 방법을 보여주기 위해 HTML을 JSON으로 변환했지만, 어떤 유형의 데이터든 Workers KV에 캐시할 수 있어요. 예를 들어 API 응답, HTML 콘텐츠, 또는 요청 간 유지하고 싶은 다른 어떤 데이터든 캐시할 수 있어요.