跳转到内容
搜索文档

使用 Workers KV 缓存数据

在 Workers KV 中缓存数据或 API 响应以提升应用性能

最后更新 查看 MarkdownAgent 设置

Workers KV 可用作持久、单一、全局缓存,Cloudflare Workers 可访问它以加速应用。 Workers KV 中缓存的数据也可从所有其他 Cloudflare 位置访问,并持久保存直到过期或删除。

在 Workers 应用中从外部资源获取数据后,你可以将数据写入 Workers KV。 在后续 Worker 请求(同一区域或其他区域)中,你可以从 Workers KV 读取缓存数据,而不是调用外部 API。 这提升了 Worker 应用的性能和弹性,同时减少外部资源的负载。

本示例展示如何在 Workers KV 中缓存数据,以及如何在 Worker 应用中从 Workers KV 读取缓存数据。

从 Worker 应用向 Workers KV 缓存数据

在以下 index.ts 文件中,Worker 从外部服务器获取数据并将响应缓存在 Workers KV 中。如果数据已缓存在 Workers KV 中,Worker 从 Workers KV 读取缓存数据,而不是调用外部 API。

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 内容,或任何其他希望在请求之间持久化的数据。

相关资源

这篇文档对您有帮助吗?