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 = ""

总结

Durable Objects 保证同名实例的强一致,适合会话与计数等场景,KV 则用于低一致性配置与缓存。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部