Cloudflare Workers Durable Objects 与 KV 实战Durable Object 示例export class Counter { constructor(state, env) { this.state = state; } async fetch(req) { const url = new URL(req.url); if (url.pathname === '/inc') { const v = (await this.state.storage.get('v')) || 0; await this.state.storage.put('v', v + 1); return new Response(String(v + 1)); } const v = (await this.state.storage.get('v')) || 0; return new Response(String(v)); } } export default { async fetch(req, env) { const id = env.COUNTER.idFromName('global'); const obj = env.COUNTER.get(id); return obj.fetch(req); } }; KV 使用示例const value = await env.CONFIG.get('feature_flag'); 绑定(wrangler.toml)[[durable_objects.bindings]] name = "COUNTER" class_name = "Counter" [[kv_namespaces]] binding = "CONFIG" id = "<namespace-id>" 总结Durable Objects 保证同名实例的强一致,适合会话与计数等场景,KV 则用于低一致性配置与缓存。

发表评论 取消回复