---

title: Cloudflare Workers Durable Objects 与 KV 实战

keywords:

  • Workers
  • Durable Objects
  • KV
  • 边缘存储
  • 一致性

description: 在 Workers 中使用 Durable Objects 实现会话一致性,并结合 KV 进行配置与缓存存取。

categories:

  • 文章资讯
  • 技术教程

---

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 则用于低一致性配置与缓存。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部