关于 cloudflare-worker
面向 Cloudflare Workers 开发者的 TypeScript 技能,涵盖请求处理、存储选型、Durable Objects 和队列的开发模式。
主要功能
- 01TypeScript Worker 开发模式
- 02KV、D1 和 R2 存储指南
- 03Durable Objects 使用模式
- 04队列生产者与消费者模式
- 05项目结构和 Hono 示例
适用场景
- 01为 Worker 数据选择存储方案
- 02组织 TypeScript Worker 项目
- 03实现实时协调功能
- 04异步处理任务
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ majesticlabs-dev/ majestic-marketplace --skill cloudflare-worker安装后在 Claude Code 中输入/cloudflare-worker确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/durable-objects.mdhono.mdqueues-testing.mdsetup.mdstorage.md详细介绍
Cloudflare Workers
TypeScript Workers 的开发模式。
相关技能(majestic-devops):
wrangler-coder:CLI 部署、密钥、测试、多环境cloudflare-coder:使用 Terraform/OpenTofu 配置基础设施
核心原则
边缘优先思维
- 默认无状态:Workers 不会在请求之间持久保存状态
- 全球分发:代码运行在全球 300 多个数据中心
- 针对冷启动优化:V8 隔离区可在几毫秒内启动
- 请求/响应模型:每次调用处理一个请求
存储选择
| 存储 | 用例 | 一致性 | 延迟 |
|---|---|---|---|
| KV | 配置、标志、缓存数据 | 最终一致 | ~10ms |
| D1 | 关系型数据、事务 | 强一致(单一区域) | ~30-50ms |
| R2 | 文件、图像、大型对象 | 强一致 | ~50-100ms |
| Durable Objects | 实时状态、WebSockets | 强一致(单个对象内) | ~50ms |
| Queues | 异步处理、批处理 | 至少一次 | 异步 |
项目结构
my-worker/
├── src/
│ ├── index.ts # Entry point
│ ├── routes/ # Route handlers
│ ├── services/ # Business logic
│ └── types.ts # Type definitions
├── test/
├── wrangler.toml # Cloudflare config
├── package.json
└── tsconfig.json
快速开始
最简 wrangler.toml
name = "my-worker"
main = "src/index.ts"
compatibility_date = "2024-12-01"
compatibility_flags = ["nodejs_compat"]
有关包含所有绑定的完整配置,请参阅 references/setup.md。
基础 Hono 应用
import { Hono } from 'hono';
import { Env } from './types';
const app = new Hono<{ Bindings: Env }>();
app.get('/', (c) => c.json({ status: 'ok' }));
app.onError((err, c) => c.json({ error: 'Internal Error' }, 500));
app.notFound((c) => c.json({ error: 'Not Found' }, 404));
export default app;
有关路由组织和中间件模式,请参阅 references/hono.md。
存储快速参考
KV(键值)
await env.CACHE.get('key', 'json');
await env.CACHE.put('key', value, { expirationTtl: 3600 });
await env.CACHE.delete('key');
D1(SQLite)
const user = await env.DB.prepare('SELECT * FROM users WHERE id = ?')
.bind(id).first();
R2(对象存储)
await env.STORAGE.put('path/file.json', JSON.stringify(data));
const object = await env.STORAGE.get('path/file.json');
有关缓存模式、迁移和查询,请参阅 references/storage.md。
Durable Objects
适用于:实时协调、WebSockets、速率限制、分布式锁。
// Get DO stub
const id = c.env.COUNTER.idFromName('my-counter');
const stub = c.env.COUNTER.get(id);
const response = await stub.fetch(new Request('http://do/increment'));
有关完整模式(包括 WebSocket 休眠),请参阅 references/durable-objects.md。
Queues
// Producer
await env.QUEUE.send({ type: 'email', payload: { to: '[email protected]' } });
// Consumer (add to default export)
async queue(batch: MessageBatch, env: Env) {
for (const msg of batch.messages) {
try { await process(msg.body); msg.ack(); }
catch { msg.retry(); }
}
}
有关消费者模式和测试设置,请参阅 references/queues-testing.md。
CLI 命令
# Development
wrangler dev # Start local server
wrangler dev --remote # Dev with remote bindings
# Deploy
wrangler deploy
# D1
wrangler d1 migrations apply my-database
# Secrets
wrangler secret put API_KEY
# Logs
wrangler tail
反模式
| 不要这样做 | 应改为 |
|---|---|
| 使用 Service Worker 格式 | 使用 ES 模块 |
对缓存写入使用 await | 使用 waitUntil 实现非阻塞操作 |
| 在 KV 中存储大型值(>25MB) | 使用 R2 存储文件 |
使用 server.accept() 处理 WebSockets | 使用 ctx.acceptWebSocket()(休眠 API) |
| 阻塞等待分析/日志记录 | 使用 waitUntil 执行后台任务 |
| 假定 KV 具有即时一致性 | 对一致性要求严格的场景使用 D1 或 DOs |
资源
评论
支持 Markdown