适合人群:
- 已经用
wrangler创建并运行过 Worker - 想用 KV 做 配置中心 / 灰度发布 / 轻量缓存
- 不想引入复杂数据库(D1 / 外部 DB)
一、Cloudflare KV 是什么?
Cloudflare KV 是一个 全球分布式 Key-Value 存储 ,可以在 Worker 边缘节点中直接读写。
核心特点:
- 🌍 全球可访问,离用户最近
- ⚡ 读取极快(毫秒级)
- 🔁 最终一致性(不是强一致)
- 📦 适合「读多写少」的场景
典型用途:
- 配置中心
- 功能开关(Feature Flag)
- 灰度 / A/B
- 轻量缓存
- 白名单 / 黑名单
二、前置条件
在开始前,你需要已经:
- ✅ 安装 Node.js(18+)
- ✅ 安装 Wrangler
- ✅ 能运行以下命令
plain
npx wrangler dev
三、创建 KV Namespace
1️⃣ 创建 KV
在 Worker 项目根目录执行:
plain
npx wrangler kv:namespace create APP_KV
输出示例:
plain
🌀 Creating namespace with title "app-kv"
✨ Success!
Add the following to your wrangler.toml:
[[kv_namespaces]]
binding = "APP_KV"
id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx"
2️⃣ 绑定到 <font style="color:rgb(0, 0, 0);">wrangler.toml</font>
编辑 <font style="color:rgb(0, 0, 0);">wrangler.toml</font>:
plain
name = "my-worker"
main = "src/index.ts"
compatibility_date = "2025-01-01"
[[kv_namespaces]]
binding = "APP_KV"
id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx"
📌 说明:
<font style="color:rgb(0, 0, 0);">binding</font>:Worker 代码中访问 KV 的变量名<font style="color:rgb(0, 0, 0);">id</font>:KV Namespace 的唯一 ID
四、本地开发如何使用 KV(重点)
⚠️ 默认行为
plain
npx wrangler dev
👉 不会访问线上 KV
✅ 推荐方式(最接近生产)
plain
npx wrangler dev --remote
- 直接使用 Cloudflare 真实 KV
- 行为与线上一致
- 推荐开发阶段使用
五、在 Worker 中使用 KV
1️⃣ 读取 KV
plain
export default {
async fetch(request: Request, env: Env) {
const value = await env.APP_KV.get("hello")
return new Response(value ?? "KV is empty")
}
}
2️⃣ 写入 KV
plain
await env.APP_KV.put("hello", "world")
3️⃣ 删除 KV
plain
await env.APP_KV.delete("hello")
六、存储 JSON 数据(真实项目必备)
写入 JSON
plain
await env.APP_KV.put(
"config:gray",
JSON.stringify({
enabled: true,
percent: 10
})
)
读取 JSON(推荐方式)
plain
const grayConfig = await env.APP_KV.get("config:gray", "json")
if (grayConfig?.enabled) {
// 灰度逻辑
}
📌 使用 <font style="color:rgb(0, 0, 0);">"json"</font> 参数,KV 会自动 <font style="color:rgb(0, 0, 0);">JSON.parse</font>
七、KV 的过期时间(TTL)
1️⃣ 设置 TTL(秒)
plain
await env.APP_KV.put("token:user123", "abc", {
expirationTtl: 600 // 10 分钟
})
2️⃣ 设置绝对过期时间
plain
await env.APP_KV.put("once", "value", {
expiration: Math.floor(Date.now() / 1000) + 3600
})
八、使用前缀管理配置(推荐)
Key 设计示例
plain
config:global
config:gray
config:feature:search
config:feature:beta
列出某类 Key
plain
const list = await env.APP_KV.list({
prefix: "config:"
})
return new Response(JSON.stringify(list.keys))
九、使用 CLI 操作 KV(非常实用)
写入
plain
npx wrangler kv:key put config:gray '{"enabled":true,"percent":20}' \
--namespace-id xxxxxxxxx
读取
plain
npx wrangler kv:key get config:gray \
--namespace-id xxxxxxxxx
删除
plain
npx wrangler kv:key delete config:gray \
--namespace-id xxxxxxxxx
👉 非常适合 线上紧急改配置
十、实战示例:灰度发布
plain
export default {
async fetch(request: Request, env: Env) {
const gray = await env.APP_KV.get("config:gray", "json")
if (gray?.enabled) {
const hit = Math.random() * 100 < gray.percent
if (hit) {
return fetch("https://gray.example.com", request)
}
}
return fetch("https://stable.example.com", request)
}
}
📌 不改代码,只改 KV,即可调整灰度比例
十一、KV 的限制与注意事项
❌ 最终一致性
- 写入后,全球节点同步需要几秒
- 不适合强一致业务
不要用 KV 存:
- 余额
- 库存
- 订单状态
❌ 不适合高频写
适合:
- 配置
- 状态标记
- 缓存
十二、KV 与其他存储对比
| 存储 | 特点 | 适用 |
|---|---|---|
| KV | 快、简单 | 配置 / 灰度 |
| D1 | SQL | 业务数据 |
| Durable Object | 强一致 | 计数 / 会话 |
十三、推荐架构(非常实用)
plain
Worker
├─ KV(配置 / 灰度)
├─ Cache API(缓存)
└─ Origin(源站)
👉 KV 控制行为,Cache 提升性能
总结
Cloudflare KV 是:
- 一个 边缘配置中心
- 一个 无需部署即可生效的控制系统
- 一个 Worker 的最佳搭档
如果你已经在用 Cloudflare Worker,KV 几乎是必用组件。