# Cloudflare Workers Durable Objects 与 KV 实战
## Durable Object 示例
```js
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 使用示例
```js
const value = await env.CONFIG.get('feature_flag');
```
## 绑定(wrangler.toml)
```toml
[[durable_objects.bindings]]
name = "COUNTER"
class_name = "Counter"
[[kv_namespaces]]
binding = "CONFIG"
id = "

发表评论 取消回复