Workers KV
KV 读写与缓存模式。
Workers KV
这一课你将能做到
- 创建 KV Namespace 并在 Worker 中完成读、写、列、删操作
- 根据业务场景选择正确的 KV 缓存模式(TTL、元数据、列表前缀)
- 理解 KV 的「最终一致性」语义,并能判断它和 Redis 的适用边界
为什么要学
你的 Next.js 前端需要一份「全站配置」来控制导航栏、Banner 文案、全局开关。如果每次请求都去读数据库,中心机房延迟 80ms,用户体验就崩了。如果放进 Redis,运维又要多维护一套集群。KV 就是专为这种「读多写少、边缘就近」的场景设计的。
人话:KV 是一个全球分布的键值存储。你写一次,Cloudflare 会自动把数据同步到全球所有边缘节点。下次用户在北京请求,直接从北京的节点读到值——不是去中心机房,不是去 Redis,而是从本地缓存读。
先建立图像
写入: [Worker] ── PUT ──> [KV 中心存储]
│
异步复制到全球节点
│
┌─────────────────────┼─────────────────────┐
▼ ▼ ▼
[北京节点] [纽约节点] [伦敦节点]
│ │ │
读取: 5ms 读取: 8ms 读取: 6ms
这就是 KV 的核心特点:写入后最终一致,但读取极快。
跟着做
步骤 1:创建 Namespace
npx wrangler kv namespace create "MY_KV"
成功后你会得到一段 toml 配置,把它复制到 wrangler.toml:
[[kv_namespaces]]
binding = "MY_KV"
id = "0xxxxxxxxxxxxxxxxxxxxxxxxx"
步骤 2:在 Worker 中读写
export interface Env {
MY_KV: KVNamespace;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
const key = url.searchParams.get('key') ?? 'default';
if (request.method === 'GET') {
const value = await env.MY_KV.get(key);
return value ? Response.json({ key, value }) : new Response('Not Found', { status: 404 });
}
if (request.method === 'PUT') {
const body = await request.text();
await env.MY_KV.put(key, body, { expirationTtl: 3600 }); // 1 小时 TTL
return new Response('OK', { status: 201 });
}
if (request.method === 'DELETE') {
await env.MY_KV.delete(key);
return new Response('Deleted');
}
return new Response('Method Not Allowed', { status: 405 });
},
} satisfies ExportedHandler<Env>;
步骤 3:带元数据的写入
await env.MY_KV.put(key, body, {
expirationTtl: 86400, // 24 小时后过期
metadata: { updatedBy: 'admin', version: '2' },
});