Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

Workers KV でデータをキャッシュする

Workers KV にデータや API レスポンスをキャッシュし、アプリケーションのパフォーマンスを向上させます

最終更新 Markdown で表示Agent セットアップ

Workers KV は、Cloudflare Workers からアクセスできる永続的で単一のグローバルキャッシュとして使え、アプリケーションを高速化できます。 Workers KV にキャッシュしたデータは、ほかの Cloudflare ロケーションからもアクセスでき、有効期限切れまたは削除まで残ります。

Workers アプリケーションで外部リソースからデータを取得したあと、そのデータを Workers KV に書き込めます。 以降の Worker リクエスト(同じリージョンでも他のリージョンでも)では、外部 API を呼ばずに Workers KV からキャッシュ済みデータを読み取れます。 これにより、Worker アプリケーションのパフォーマンスと耐障害性が向上し、外部リソースの負荷も減ります。

この例では、Worker アプリケーションで Workers KV にデータをキャッシュし、キャッシュ済みデータを読み取る方法を示します。

Worker アプリケーションから Workers KV にデータをキャッシュする

次の index.ts では、Worker が外部サーバーからデータを取得し、レスポンスを Workers KV にキャッシュします。データがすでに Workers KV にある場合は、外部 API を呼ばずに Workers KV からキャッシュ済みデータを読み取ります。

index.tsjs
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 にキャッシュします。

この例では HTML を JSON に変換し、Workers KV で JSON データをキャッシュする方法を示しています。ただし、Workers KV には任意の種類のデータをキャッシュできます。たとえば、API レスポンス、HTML コンテンツ、リクエストをまたいで残したいその他のデータをキャッシュできます。

関連リソース

役に立ちましたか?