用途
本技能面向在 Cloudflare Workers 上使用 Hono 框架进行开发的场景。Hono 最初就是为 Cloudflare Workers 构建的,因此对 Cloudflare 生态提供一等支持,包括 KV、D1、R2、Durable Objects、Queues 等。
适用场景包括:构建全球分发的边缘 API;需要 D1 提供的无服务器 SQLite;使用 Durable Objects 构建实时应用;使用 R2 存储文件;使用 KV 做快速键值存储;将全栈应用部署到 Pages。
主要能力
- 原生 Workers 支持
- 类型安全的绑定访问
- KV、D1、R2、Durable Objects 集成
- 静态资源服务
- Cloudflare Pages 支持
- 队列与定时处理器
使用方式
创建项目
npm create hono@latest my-app
# 选择:cloudflare-workers
cd my-app
npm install
npm run dev
项目结构:
my-app/
├── src/
│ └── index.ts # 主入口
├── wrangler.toml # Cloudflare 配置
├── package.json
└── tsconfig.json
基础应用:
// src/index.ts
import { Hono } from 'hono'
const app = new Hono()
app.get('/', (c) => c.text('Hello Cloudflare Workers!'))
export default app
部署:
# 部署到 Cloudflare
npx wrangler deploy
# 本地开发
npx wrangler dev
环境绑定
通过泛型定义 Bindings 类型,可获得完全类型化的 c.env 访问,涵盖环境变量、KV 命名空间、D1 数据库、R2 存储桶、Durable Objects 和 Queues。
type Bindings = {
API_KEY: string
DATABASE_URL: string
MY_KV: KVNamespace
DB: D1Database
BUCKET: R2Bucket
COUNTER: DurableObjectNamespace
MY_QUEUE: Queue
}
const app = new Hono<{ Bindings: Bindings }>()
wrangler.toml 中配置 vars、kv_namespaces、d1_databases、r2_buckets、queues.producers 等绑定。
KV 存储
支持 get、getWithMetadata、put(可设置 expirationTtl 过期时间)、delete、list(支持 prefix 与 limit)等操作,并可为键值附加 metadata。
D1 数据库
通过 c.env.DB.prepare(...).bind(...).all()/first()/run() 执行查询、插入、更新、删除,并支持 batch 批量操作。
R2 对象存储
支持上传(put,可设置 httpMetadata 的 contentType)、下载(get,返回 body 与 ETag)、删除(delete)、列表(list,支持 prefix 与 limit)。
Durable Objects
定义 Durable Object 类(如 Counter),在 fetch 中通过 state.storage 读写持久化状态;在 Hono 中通过 idFromName 与 get 获取 stub 并调用。wrangler.toml 中需配置 durable_objects.bindings 与 migrations。
Queues
生产者通过 c.env.MY_QUEUE.send 或 sendBatch 发送消息;消费者在默认导出的 queue 方法中处理 MessageBatch,可调用 message.ack() 或 message.retry()。
静态资源
可在 wrangler.toml 中通过 assets = { directory = "public" } 提供静态文件,也可使用 hono/cloudflare-workers 的 serveStatic 中间件。
定时事件(Cron)
在默认导出的 scheduled 方法中根据 event.cron 执行不同任务,并在 wrangler.toml 的 [triggers] 中配置 crons。
Cloudflare Pages
在 functions/[[path]].ts 中使用 hono/cloudflare-pages 的 handle 导出 onRequest,可设置 basePath。中间件中应通过 c.env 访问环境变量,而非在模块顶层访问。
常用命令
npx wrangler dev
npx wrangler deploy
npx wrangler d1 create my-database
npx wrangler d1 execute my-database --file=schema.sql
npx wrangler kv:namespace create MY_KV
npx wrangler r2 bucket create my-bucket
npx wrangler tail
限制
资料未提供关于收费、价格、性能上限或具体配额的信息,暂未提供。版本信息为 Hono 4.x、Wrangler 3.x,最后更新于 2025 年 1 月,许可证为 MIT。