返回首页
⚙️ 后端 / 架构

Hono + Cloudflare Workers 2026:边缘计算完整实战指南

边缘计算是 2026 年后端标配。本文 Hono / Cloudflare Workers / Vercel Edge / Deno 4 大方案对比 + 6 个实战 + 性能基准。

Hono · Cloudflare Workers · 边缘计算 · Vercel Edge · Deno · Workers AI · WASM · RPC
��

今日技术简讯

📰 技术简讯 · 2026-08-24

今日聚合 6 条热门技术内容(中文素材优先)。

🤖 AI / LLM

1. Cloudflare 推出 Workers AI 2.0

2. Hono 推出 4.0

  • 链接https://hono.dev/blog/hono-4-0
  • 来源:Hono
  • 摘要:Hono 4.0 推出 WebAssembly 适配器,支持浏览器 / Deno / Bun / Node / Workers 全平台。

🎨 前端 / Web

3. Vercel 推出 Edge Functions 2.0

4. Netlify 推出 Edge Functions GA

⚙️ 后端 / 架构

5. Deno 推出 2.2

🚀 独立开发 / OPC

6. 即刻"边缘计算"专题


数据来源:掘金 / InfoQ 中文 / 即刻 / 少数派 / HN 采集日期:2026-08-24 (UTC+8)

��

今日深度文

Hono + Cloudflare Workers 2026:边缘计算完整实战指南

一句话结论:2026 年后端 = 边缘计算。Cloudflare Workers 全球 300+ 节点,延迟 < 30ms,成本降低 90%。本文 Hono / Workers / Vercel Edge / Deno 4 大方案对比 + 实战。

背景

2026 年边缘计算成为后端新范式:

传统集中式后端(AWS us-east-1):
- 用户 → 全球 → us-east-1 服务器
- 平均延迟:200-500ms
- 流量集中、扩容困难
- 冷启动 5-30 秒

边缘计算(Cloudflare Workers / Vercel Edge):
- 用户 → 最近边缘节点 → 全球 300+ 节点
- 平均延迟:< 30ms(10x 快)
- 自动扩容 / 零运维
- 冷启动 < 5ms

为什么边缘计算是 2026 年关键:

  1. 延迟:用户对响应速度敏感(< 100ms)
  2. 成本:Workers 按请求计费,比 EC2 便宜 10x
  3. 可扩展:无需考虑容量规划
  4. 多区域:天然支持全球部署
  5. AI 原生:Workers AI 跑端侧 LLM

4 大方案对比

方案 运行时 节点数 冷启动 计费
Cloudflare Workers V8 Isolates 300+ < 5ms 按请求
Vercel Edge V8 Isolates 18+ < 25ms 按调用
Netlify Edge Deno 50+ < 50ms 按调用
Deno Deploy Deno 35+ < 5ms 按请求

Hono 框架简介

Hono 是 2026 年最流行的边缘计算框架:

// 极简 Hono 应用
import { Hono } from 'hono';

const app = new Hono();

app.get('/', (c) => c.text('Hello from Hono!'));
app.get('/api/users/:id', (c) => c.json({ id: c.param('id') }));

export default app;

优势

  • 极小(< 14KB)
  • 快(基于 Web Standards)
  • 跨平台(Cloudflare / Vercel / Deno / Bun / Node)
  • TypeScript 原生

Cloudflare Workers 完整示例

// src/index.ts - Cloudflare Workers + Hono
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { jwt } from 'hono/jwt';

type Bindings = {
  DB: D1Database;
  KV: KVNamespace;
  AI: Ai;
};

const app = new Hono<{ Bindings: Bindings }>();

// CORS 中间件
app.use('*', cors({ origin: '*' }));

// 路由
app.get('/', (c) => c.text('Hello from Cloudflare Workers!'));

app.get('/api/users', async (c) => {
  const { results } = await c.env.DB.prepare(
    'SELECT * FROM users LIMIT 10'
  ).all();
  return c.json(results);
});

app.post('/api/users', async (c) => {
  const body = await c.req.json();
  await c.env.DB.prepare(
    'INSERT INTO users (name, email) VALUES (?, ?)'
  ).bind(body.name, body.email).run();
  return c.json({ success: true });
});

// JWT 鉴权
app.use('/api/protected/*', jwt({ secret: 'your-secret-key' }));
app.get('/api/protected/profile', (c) => c.json({ user: c.get('jwtPayload') }));

// Workers AI 推理
app.post('/api/ai/chat', async (c) => {
  const { messages } = await c.req.json();
  const response = await c.env.AI.run('@cf/meta/llama-3-8b-instruct', {
    messages,
  });
  return c.json(response);
});

export default app;

wrangler.toml 配置

# wrangler.toml - Cloudflare Workers 配置
name = "my-app"
main = "src/index.ts"
compatibility_date = "2026-08-01"

# D1 数据库
[[d1_databases]]
binding = "DB"
database_name = "my-db"
database_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

# KV 存储
[[kv_namespaces]]
binding = "KV"
id = "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy"

# AI 绑定
[ai]
binding = "AI"

# R2 存储
[[r2_buckets]]
binding = "STORAGE"
bucket_name = "my-bucket"

# 环境变量
[vars]
API_URL = "https://api.example.com"

# 定时触发器
[triggers]
crons = ["0 */6 * * *"]  # 每 6 小时执行一次

# 队列
[[queues.producers]]
queue = "my-queue"
binding = "QUEUE"

[[queues.consumers]]
queue = "my-queue"
max_batch_size = 10
max_retries = 3
# 部署
npx wrangler deploy

# 本地开发
npx wrangler dev

# 查看日志
npx wrangler tail

# 数据库迁移
npx wrangler d1 migrations apply my-db --remote

Vercel Edge Functions 示例

// app/api/hello/route.ts - Vercel Edge + Hono
import { Hono } from 'hono';

export const runtime = 'edge';
export const preferredRegion = 'auto';

const app = new Hono();

app.get('/api/hello', (c) => c.json({ message: 'Hello from Vercel Edge!' }));

export const GET = app.fetch;
export const POST = app.fetch;
// next.config.js
module.exports = {
  experimental: {
    runtime: 'edge',
  },
};

Netlify Edge Functions 示例

// netlify/edge-functions/hello.ts - Netlify Edge + Deno
import { Hono } from 'hono';

export default async (request: Request) => {
  const app = new Hono();
  app.get('/hello', () => new Response('Hello from Netlify Edge!'));
  return app.fetch(request);
};

export const config = { path: '/api/*' };

Deno Deploy 示例

// main.ts - Deno Deploy
import { Hono } from 'hono';

const app = new Hono();

app.get('/', (c) => c.text('Hello from Deno Deploy!'));

Deno.serve(app.fetch);

实战 1:完整的 CRUD API(Cloudflare Workers)

// src/index.ts - 完整 CRUD 应用
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { logger } from 'hono/logger';

type Env = {
  DB: D1Database;
};

const app = new Hono<{ Bindings: Env }>();

app.use('*', logger());
app.use('/api/*', cors());

// 列表
app.get('/api/posts', async (c) => {
  const { results } = await c.env.DB.prepare(
    'SELECT * FROM posts ORDER BY created_at DESC LIMIT 20'
  ).all();
  return c.json({ posts: results });
});

// 详情
app.get('/api/posts/:id', async (c) => {
  const id = c.param('id');
  const post = await c.env.DB.prepare(
    'SELECT * FROM posts WHERE id = ?'
  ).bind(id).first();
  
  if (!post) return c.json({ error: 'Not found' }, 404);
  return c.json(post);
});

// 创建
app.post('/api/posts', async (c) => {
  const body = await c.req.json();
  await c.env.DB.prepare(
    'INSERT INTO posts (title, content) VALUES (?, ?)'
  ).bind(body.title, body.content).run();
  return c.json({ success: true }, 201);
});

// 更新
app.put('/api/posts/:id', async (c) => {
  const id = c.param('id');
  const body = await c.req.json();
  await c.env.DB.prepare(
    'UPDATE posts SET title = ?, content = ? WHERE id = ?'
  ).bind(body.title, body.content, id).run();
  return c.json({ success: true });
});

// 删除
app.delete('/api/posts/:id', async (c) => {
  const id = c.param('id');
  await c.env.DB.prepare('DELETE FROM posts WHERE id = ?').bind(id).run();
  return c.json({ success: true });
});

export default app;

实战 2:Workers AI 端侧推理

// AI 聊天应用
import { Hono } from 'hono';
import { streamText } from 'hono/streaming';

type Env = { AI: Ai };

const app = new Hono<{ Bindings: Env }>();

app.post('/api/chat', async (c) => {
  const { messages } = await c.req.json();
  
  return streamText(c, async (stream) => {
    const response = await c.env.AI.run(
      '@cf/meta/llama-3-8b-instruct',
      {
        messages,
        stream: true,
      }
    );
    
    for await (const chunk of response) {
      await stream.write(chunk.response);
    }
  });
});

app.post('/api/embeddings', async (c) => {
  const { text } = await c.req.json();
  const embeddings = await c.env.AI.run('@cf/baai/bge-base-en-v1.5', {
    text: [text],
  });
  return c.json(embeddings);
});

export default app;

实战 3:边缘缓存 + KV 存储

// 边缘缓存 API
import { Hono } from 'hono';

type Env = { KV: KVNamespace };

const app = new Hono<{ Bindings: Env }>();

app.get('/api/data/:key', async (c) => {
  const key = c.param('key');
  
  // 1. 查 KV 缓存
  const cached = await c.env.KV.get(key);
  if (cached) {
    return c.json(JSON.parse(cached), 200, {
      'X-Cache': 'HIT',
    });
  }
  
  // 2. 缓存未命中,查数据库
  const data = await fetchDataFromDB(key);
  
  // 3. 写入 KV(TTL 5 分钟)
  await c.env.KV.put(key, JSON.stringify(data), {
    expirationTtl: 300,
  });
  
  return c.json(data, 200, {
    'X-Cache': 'MISS',
  });
});

export default app;

实战 4:队列异步处理

// 队列消费者
export interface Env {
  QUEUE: Queue;
}

export default {
  async queue(batch: MessageBatch<any>, env: Env): Promise<void> {
    for (const message of batch.messages) {
      const { userId, action } = message.body;
      
      // 处理任务(发邮件 / 生成报告 / 同步数据)
      await processTask(userId, action);
      
      // 确认消息
      message.ack();
    }
  },
};
// 队列生产者
app.post('/api/jobs', async (c) => {
  const { userId, action } = await c.req.json();
  await c.env.QUEUE.send({ userId, action });
  return c.json({ queued: true });
});

实战 5:Cron 定时任务

// 定时任务 - 每 6 小时清理过期数据
export default {
  async scheduled(event: ScheduledEvent, env: Env): Promise<void> {
    const { cron } = event;
    console.log(`Cron triggered: ${cron}`);
    
    // 清理过期数据
    await env.DB.prepare(
      'DELETE FROM sessions WHERE expires_at < ?'
    ).bind(Date.now()).run();
    
    // 预热缓存
    await env.KV.put('popular-posts', JSON.stringify(
      await env.DB.prepare(
        'SELECT * FROM posts ORDER BY views DESC LIMIT 100'
      ).all()
    ), { expirationTtl: 3600 });
  },
};

实战 6:WebAssembly 模块

// 调用 WASM 模块(图像处理)
import imageWasm from './image-processor.wasm';

app.post('/api/process-image', async (c) => {
  const formData = await c.req.formData();
  const image = formData.get('image') as File;
  const buffer = await image.arrayBuffer();
  
  // 实例化 WASM
  const wasmInstance = await WebAssembly.instantiate(imageWasm, {
    env: {
      memory: new WebAssembly.Memory({ initial: 256 }),
    },
  });
  
  // 调用 WASM 函数处理图像
  const result = wasmInstance.exports.process_image(buffer);
  
  return new Response(result, {
    headers: { 'Content-Type': 'image/png' },
  });
});

实战 7:RPC 类型安全

// 服务端 RPC
import { Hono } from 'hono';
import { hc } from 'hono/client';

const app = new Hono()
  .get('/users/:id', (c) => c.json({ id: c.param('id'), name: 'Alice' }));

export type AppType = typeof app;

// 客户端(完全类型安全)
const client = hc<AppType>('https://api.example.com');
const res = await client.users[':id'].$get({ param: { id: '123' } });
const data = await res.json();  // 类型自动推断

实战 8:实时 WebSocket

// Durable Objects 实现的聊天室
import { Hono } from 'hono';
import { upgradeWebSocket } from 'hono/cloudflare-workers';

const app = new Hono();

app.get('/ws', upgradeWebSocket((c) => ({
  onOpen(evt, ws) {
    console.log('Connected');
  },
  onMessage(evt, ws) {
    // 广播消息给所有客户端
    ws.send(`Echo: ${evt.data}`);
  },
  onClose() {
    console.log('Closed');
  },
})));

export default app;

性能基准

冷启动时间

平台 冷启动
Cloudflare Workers < 5ms
Vercel Edge < 25ms
Netlify Edge < 50ms
Deno Deploy < 5ms
AWS Lambda 200-1000ms
EC2 30-60s

全球延迟

平台 北美 欧洲 亚洲
Cloudflare Workers 15ms 18ms 22ms
Vercel Edge 25ms 35ms 45ms
AWS Lambda us-east-1 50ms 150ms 250ms
传统服务器 100ms 300ms 500ms

成本对比(100 万请求/月)

平台 费用
Cloudflare Workers $0.50
Vercel Edge $2.00
AWS Lambda $20.00
EC2 t3.micro $8.00(持续)

选型决策树

你的项目特点?
├─ 全球用户 + 延迟敏感 → Cloudflare Workers ✅
├─ Next.js 应用 → Vercel Edge ✅
├─ 已有 Deno 代码 → Deno Deploy ✅
├─ 简单边缘函数 → Netlify Edge
└─ 需要长任务 / 大文件 → 仍然用 AWS Lambda

你的预算?
├─ 极低(< $10/月) → Cloudflare Workers(免费额度最大)
├─ 中等 → Vercel Edge(开发体验最好)
└─ 高 → AWS Lambda(功能最全)

你需要 AI 吗?
├─ 是 → Cloudflare Workers(Workers AI 免费跑 Llama-3)
└─ 否 → 任何平台都行

部署到 Cloudflare 的完整流程

# 1. 安装 wrangler
npm install -g wrangler

# 2. 登录
wrangler login

# 3. 创建项目
wrangler init my-app

# 4. 本地开发
wrangler dev

# 5. 部署
wrangler deploy

# 6. 创建 D1 数据库
wrangler d1 create my-db
wrangler d1 migrations create my-db init
wrangler d1 migrations apply my-db --local
wrangler d1 migrations apply my-db --remote

# 7. 创建 KV 命名空间
wrangler kv:namespace create MY_KV
wrangler kv:namespace create MY_KV --preview

# 8. 创建 R2 存储桶
wrangler r2 bucket create my-bucket

# 9. 创建队列
wrangler queues create my-queue

# 10. 设置密钥
wrangler secret put API_KEY

总结

边缘计算 = 2026 年后端新范式

技术层面

  • ✅ 全球 300+ 节点,延迟 < 30ms
  • ✅ 冷启动 < 5ms(vs Lambda 200ms)
  • ✅ Workers AI 免费跑 Llama-3-8B
  • ✅ 4 大平台成熟:Cloudflare / Vercel / Netlify / Deno
  • ✅ Hono 框架跨平台统一

商业层面

  • ✅ 成本降低 10-100x
  • ✅ 零运维 / 自动扩容
  • ✅ 全球部署无需复杂 CDN

8 大实战场景

  • CRUD API / AI 推理 / 边缘缓存 / 队列异步 / Cron 任务 / WASM / RPC / WebSocket

行动建议

  1. 新项目直接用 Hono + Cloudflare Workers
  2. Next.js 项目用 Vercel Edge
  3. 评估迁移现有 API 到边缘
  4. 关注 Workers AI(端侧 LLM)

边缘计算不是未来,是现在。10x 性能 + 90% 成本降低,所有项目都应该认真评估。

Hono 完整生态详解

Hono 是边缘计算领域最流行的框架,GitHub 30k+ stars,已经成为 Cloudflare Workers 的事实标准。

为什么 Hono 这么受欢迎?

对比主流框架在 Workers 上的表现:

Hono:
- 启动时间:< 1ms
- 内存占用:< 1MB
- 路由匹配:基于 Trie(O(1))
- 中间件:30+ 内置
- 学习曲线:⭐⭐(最简单)

Express:
- 启动时间:50ms
- 内存占用:> 5MB
- 不支持 Workers(需要 polyfill)

Fastify:
- 启动时间:30ms
- 内存占用:3MB
- 部分支持 Workers

Next.js API Routes:
- 启动时间:200ms
- 内存占用:> 20MB
- 与 Next.js 强耦合

Hono 的核心优势是:基于 Web Standards,可以在任何支持 fetch API 的环境运行。

Hono 完整路由示例

import { Hono } from 'hono';
import { HTTPException } from 'hono/http-exception';

const app = new Hono();

// 基础路由
app.get('/', (c) => c.text('Hello'));
app.post('/users', (c) => c.json({ created: true }));
app.put('/users/:id', (c) => c.json({ updated: c.param('id') }));
app.delete('/users/:id', (c) => c.json({ deleted: c.param('id') }));

// 路径参数
app.get('/posts/:postId/comments/:commentId', (c) => {
  return c.json({
    postId: c.param('postId'),
    commentId: c.param('commentId'),
  });
});

// 通配符
app.get('/files/*', (c) => {
  return c.text(c.req.path);
});

// 链式路由
app.route('/api/v1', v1Router);
app.route('/api/v2', v2Router);

// 分组路由
const api = new Hono();
api.get('/users', listUsers);
api.post('/users', createUser);

app.route('/api', api);

// 错误处理
app.onError((err, c) => {
  if (err instanceof HTTPException) {
    return err.getResponse();
  }
  return c.json({ error: 'Internal Error' }, 500);
});

// 404
app.notFound((c) => c.json({ error: 'Not Found' }, 404));

export default app;

Hono 中间件详解

Hono 内置 30+ 中间件,覆盖各种场景:

认证授权

import { jwt } from 'hono/jwt';
import { basicAuth } from 'hono/basic-auth';
import { bearerAuth } from 'hono/bearer-auth';

// JWT
app.use('/api/*', jwt({ secret: 'my-secret' }));

// Basic Auth
app.use('/admin/*', basicAuth({
  username: 'admin',
  password: 'secret',
}));

// Bearer Token
app.use('/api/*', bearerAuth({ token: 'my-token' }));

验证与解析

import { zValidator } from '@hono/zod-validator';
import { z } from 'zod';

const schema = z.object({
  name: z.string().min(2),
  email: z.string().email(),
});

app.post('/users',
  zValidator('json', schema),
  (c) => {
    const data = c.req.valid('json');  // 类型安全
    return c.json({ created: true });
  }
);

缓存与压缩

import { cache } from 'hono/cache';
import { compress } from 'hono/compress';

// 缓存(30 秒)
app.use('/api/*', cache({
  cacheName: 'my-cache',
  cacheControl: 'max-age=30',
}));

// 压缩响应
app.use('*', compress());

安全与 CORS

import { cors } from 'hono/cors';
import { secureHeaders } from 'hono/secure-headers';

app.use('*', cors({
  origin: ['https://example.com'],
  credentials: true,
}));

app.use('*', secureHeaders());

日志与监控

import { logger } from 'hono/logger';
import { prometheus } from '@hono/prometheus';

app.use('*', logger());

// Prometheus 指标
app.use('*', prometheus());

app.get('/metrics', (c) => c.text(prometheus.register.metrics()));

D1 数据库深度使用

Cloudflare D1 是基于 SQLite 的边缘数据库:

// 完整 D1 使用示例
type Env = { DB: D1Database };

// 批量插入
app.post('/api/users/bulk', async (c) => {
  const users = await c.req.json();
  
  // 构建批量 SQL
  const stmt = c.env.DB.prepare(
    'INSERT INTO users (name, email) VALUES (?, ?)'
  );
  
  // 使用 batch 提高性能
  const batch = users.map((u: any) =>
    stmt.bind(u.name, u.email)
  );
  
  await c.env.DB.batch(batch);
  return c.json({ inserted: users.length });
});

// 复杂查询
app.get('/api/users/search', async (c) => {
  const q = c.req.query('q');
  
  const { results } = await c.env.DB.prepare(`
    SELECT u.*, COUNT(p.id) as post_count
    FROM users u
    LEFT JOIN posts p ON p.author_id = u.id
    WHERE u.name LIKE ? OR u.email LIKE ?
    GROUP BY u.id
    ORDER BY post_count DESC
    LIMIT 20
  `).bind(`%${q}%`, `%${q}%`).all();
  
  return c.json({ users: results });
});

// 事务
app.post('/api/transfer', async (c) => {
  const { fromId, toId, amount } = await c.req.json();
  
  await c.env.DB.batch([
    c.env.DB.prepare('UPDATE accounts SET balance = balance - ? WHERE id = ?')
      .bind(amount, fromId),
    c.env.DB.prepare('UPDATE accounts SET balance = balance + ? WHERE id = ?')
      .bind(amount, toId),
  ]);
  
  return c.json({ success: true });
});

D1 性能特点:

- 全球复制(read replica)
- 单 region 写入,全球读取
- 适合读多写少场景
- 单次查询 < 100ms
- 单次写入 < 500ms

R2 对象存储

R2 是 S3 兼容的对象存储,无 egress 费用:

// 上传文件到 R2
app.post('/api/upload', async (c) => {
  const file = await c.req.parseBody();
  const image = file['image'] as File;
  
  const key = `images/${Date.now()}-${image.name}`;
  await c.env.STORAGE.put(key, image.stream(), {
    httpMetadata: { contentType: image.type },
  });
  
  return c.json({ key });
});

// 下载文件
app.get('/api/files/:key', async (c) => {
  const key = c.req.param('key');
  const object = await c.env.STORAGE.get(key);
  
  if (!object) return c.json({ error: 'Not found' }, 404);
  
  return new Response(object.body, {
    headers: {
      'Content-Type': object.httpMetadata?.contentType || 'application/octet-stream',
    },
  });
});

// 生成预签名 URL
app.get('/api/files/:key/url', async (c) => {
  const key = c.req.param('key');
  const url = await c.env.STORAGE.createPresignedUrl(key, {
    expiresIn: 3600,
  });
  return c.json({ url });
});

R2 优势:

- 无 egress 流量费(最大优势)
- S3 API 完全兼容
- 全球边缘节点
- 单次操作 < 100ms

Durable Objects 实战

Durable Objects 是 Cloudflare 的强一致性状态管理方案:

// 计数器 Durable Object
export class Counter {
  state: DurableObjectState;
  
  constructor(state: DurableObjectState) {
    this.state = state;
  }
  
  async fetch(request: Request): Promise<Response> {
    const url = new URL(request.url);
    const count = (await this.state.storage.get('count') as number) || 0;
    
    if (url.pathname === '/increment') {
      const newCount = count + 1;
      await this.state.storage.put('count', newCount);
      return new Response(JSON.stringify({ count: newCount }));
    }
    
    if (url.pathname === '/get') {
      return new Response(JSON.stringify({ count }));
    }
    
    return new Response('Not Found', { status: 404 });
  }
}

// 路由
app.get('/counter/:id/increment', async (c) => {
  const id = c.env.COUNTER.idFromName(c.req.param('id'));
  const counter = c.env.COUNTER.get(id);
  const response = await counter.fetch(new Request('https://fake/increment'));
  return c.json(await response.json());
});

Durable Objects 适用场景:

1. 实时协作(WebSocket 状态)
2. 游戏房间(玩家状态)
3. 计数器 / 排行榜
4. 限流(每用户限制)
5. 队列(任务分发)

边缘认证模式

边缘计算的认证有特殊考虑:

// JWT 认证(无状态)
import { jwt, sign, verify } from 'hono/jwt';

app.post('/api/login', async (c) => {
  const { username, password } = await c.req.json();
  
  // 验证用户
  const user = await verifyUser(username, password);
  if (!user) return c.json({ error: 'Invalid' }, 401);
  
  // 签发 JWT
  const token = await sign(
    { sub: user.id, exp: Math.floor(Date.now() / 1000) + 3600 },
    c.env.JWT_SECRET
  );
  
  return c.json({ token });
});

// 刷新 Token
app.post('/api/refresh', jwt({ secret: 'my-secret' }), async (c) => {
  const payload = c.get('jwtPayload');
  const newToken = await sign(
    { sub: payload.sub, exp: Math.floor(Date.now() / 1000) + 3600 },
    c.env.JWT_SECRET
  );
  return c.json({ token: newToken });
});

Session 存储(基于 KV):

app.post('/api/login', async (c) => {
  const sessionId = crypto.randomUUID();
  await c.env.KV.put(`session:${sessionId}`, JSON.stringify({ userId: 1 }), {
    expirationTtl: 86400,
  });
  
  return c.json({ sessionId }, 200, {
    'Set-Cookie': `session=${sessionId}; HttpOnly; Secure`,
  });
});

app.use('/api/*', async (c, next) => {
  const sessionId = c.req.header('cookie')?.split('=')[1];
  if (!sessionId) return c.json({ error: 'Unauthorized' }, 401);
  
  const session = await c.env.KV.get(`session:${sessionId}`);
  if (!session) return c.json({ error: 'Unauthorized' }, 401);
  
  c.set('session', JSON.parse(session));
  await next();
});

边缘计算的真实案例

案例 1:某全球电商网站

迁移前(AWS Lambda + RDS):

  • 全球平均延迟:250ms
  • 月成本:$15,000
  • 数据库压力:高

迁移后(Cloudflare Workers + D1):

  • 全球平均延迟:45ms(5.5x 快)
  • 月成本:$1,200(92% 降低)
  • 数据库压力:低(边缘缓存)

案例 2:某 AI 图像处理服务

迁移前(EC2 GPU 服务器):

  • 单图处理:800ms
  • 月服务器成本:$3,000

迁移后(Cloudflare Workers + Workers AI):

  • 单图处理:250ms(3.2x 快)
  • 月成本:$200(93% 降低)

案例 3:某实时聊天应用

迁移前(Socket.io + EC2):

  • 并发连接:5,000
  • 服务器:5 台 t3.medium

迁移后(Durable Objects + Workers):

  • 并发连接:100,000(20x)
  • 服务器:0(完全 serverless)

性能优化技巧

1. 路由匹配优化

// ✅ 静态路由优先(更快)
app.get('/api/users', handler);
app.get('/api/users/:id', handler);
app.get('/api/users/:id/posts', handler);

// ❌ 避免过深的动态路由
app.get('/api/:a/:c/:d/:e/:f', handler);  // 慢

2. 减少 KV 查询

// ❌ 多次查询
const user = await c.env.KV.get(`user:${id}`);
const posts = await c.env.KV.get(`posts:${id}`);

// ✅ 批量查询
const data = await c.env.KV.getMulti([
  `user:${id}`,
  `posts:${id}`,
]);

3. 使用 Streams

// ❌ 加载完整数据
const data = await fetch(url);
const json = await data.json();

// ✅ 流式处理
const response = await fetch(url, { cf: { cacheTtl: 3600 } });
return new Response(response.body, {
  headers: response.headers,
});

4. 缓存静态资源

app.get('/static/*', async (c) => {
  return c.env.ASSETS.fetch(c.req.raw);
});

监控与调试

Cloudflare Workers Analytics

app.use('*', async (c, next) => {
  const start = Date.now();
  await next();
  const duration = Date.now() - start;
  
  // 自定义指标
  console.log({
    method: c.req.method,
    path: c.req.path,
    status: c.res.status,
    duration,
  });
});

实时日志

# wrangler tail - 实时查看日志
wrangler tail --format=pretty

错误追踪

app.onError((err, c) => {
  // 发送错误到 Sentry
  console.error({
    error: err.message,
    stack: err.stack,
    path: c.req.path,
    headers: c.req.header(),
  });
  
  return c.json({ error: 'Internal Server Error' }, 500);
});

迁移实战:从 Express 到 Hono

// ❌ Express 代码(不兼容 Workers)
const express = require('express');
const app = express();

app.get('/users', async (req, res) => {
  const users = await db.query('SELECT * FROM users');
  res.json(users);
});

app.listen(3000);

// ✅ Hono 代码(兼容 Workers)
import { Hono } from 'hono';

const app = new Hono();

app.get('/users', async (c) => {
  const { results } = await c.env.DB.prepare(
    'SELECT * FROM users'
  ).all();
  return c.json(results);
});

export default app;

迁移步骤:

1. 替换框架(Hono / Itty Router)
2. 替换 res.json → c.json
3. 替换 req.body → await c.req.json()
4. 替换 req.params → c.req.param()
5. 替换数据库驱动(pg → D1 / Hyperdrive)
6. 替换文件上传(multer → formData)
7. 测试 + 部署

与传统后端架构对比

传统架构(EC2 + RDS + ALB)

用户 → DNS → ALB → EC2 (us-east-1) → RDS
延迟:200-500ms
成本:高
运维:复杂
弹性:需手动配置

边缘架构(Workers + D1 + R2)

用户 → DNS → 最近边缘节点 → Workers + D1 + R2
延迟:< 30ms
成本:极低
运维:零
弹性:自动

何时不适合边缘计算

❌ 长任务(> 30 秒):用 AWS Lambda / EC2
❌ 大文件处理(> 100MB):用 EC2 + S3
❌ 复杂状态管理:考虑 Durable Objects 或传统后端
❌ 需要特定操作系统:必须用容器

边缘计算的未来趋势

1. 边缘 AI

Cloudflare Workers AI 已经支持:

  • Llama-3-8B(免费)
  • Mistral-7B
  • BGE Embeddings
  • Whisper(语音识别)

未来所有边缘平台都会内置 AI 能力。

2. 边缘数据库

  • Cloudflare D1(SQLite)
  • Turso(边缘 SQLite)
  • Neon(边缘 Postgres)
  • PlanetScale(边缘 MySQL)

3. 边缘 GPU

Cloudflare 正在测试 GPU 支持,未来 Workers 可以运行:

  • Stable Diffusion
  • 视频生成模型
  • 3D 渲染

4. 边缘 WebAssembly

WASM 模块可以分发到所有边缘节点,毫秒级冷启动。

5. 边缘函数市场

Vercel / Cloudflare 都将推出函数市场,开发者可以发布可复用的边缘函数。

完整实战项目:构建边缘优先的 SaaS

下面是一个完整的 SaaS 应用架构:

// 主应用 - Hono + Cloudflare
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { jwt } from 'hono/jwt';
import { zValidator } from '@hono/zod-validator';
import { z } from 'zod';

type Env = {
  DB: D1Database;
  KV: KVNamespace;
  AI: Ai;
  STORAGE: R2Bucket;
  QUEUE: Queue;
};

const app = new Hono<{ Bindings: Env }>();

app.use('*', cors());

// 公共路由
app.post('/api/auth/signup',
  zValidator('json', z.object({
    email: z.string().email(),
    password: z.string().min(8),
  })),
  async (c) => {
    const { email, password } = c.req.valid('json');
    
    // 1. 创建用户到 D1
    await c.env.DB.prepare(
      'INSERT INTO users (email, password_hash) VALUES (?, ?)'
    ).bind(email, await hash(password)).run();
    
    // 2. 发送欢迎邮件(队列)
    await c.env.QUEUE.send({ type: 'welcome_email', email });
    
    return c.json({ success: true });
  }
);

app.post('/api/auth/login',
  zValidator('json', z.object({
    email: z.string().email(),
    password: z.string(),
  })),
  async (c) => {
    const { email, password } = c.req.valid('json');
    const user = await c.env.DB.prepare(
      'SELECT * FROM users WHERE email = ?'
    ).bind(email).first();
    
    if (!user || !(await verify(password, user.password_hash))) {
      return c.json({ error: 'Invalid' }, 401);
    }
    
    const token = await sign({ sub: user.id }, c.env.JWT_SECRET);
    return c.json({ token });
  }
);

// 受保护路由
app.use('/api/*', jwt({ secret: 'my-secret' }));

app.get('/api/posts', async (c) => {
  const userId = c.get('jwtPayload').sub;
  const cacheKey = `posts:${userId}`;
  
  // 尝试从 KV 缓存
  const cached = await c.env.KV.get(cacheKey);
  if (cached) return c.json(JSON.parse(cached));
  
  // 查询数据库
  const { results } = await c.env.DB.prepare(`
    SELECT * FROM posts WHERE user_id = ? ORDER BY created_at DESC
  `).bind(userId).all();
  
  // 缓存 60 秒
  await c.env.KV.put(cacheKey, JSON.stringify(results), {
    expirationTtl: 60,
  });
  
  return c.json(results);
});

app.post('/api/posts/generate', async (c) => {
  const { topic } = await c.req.json();
  
  // 使用 Workers AI 生成内容
  const aiResponse = await c.env.AI.run(
    '@cf/meta/llama-3-8b-instruct',
    {
      messages: [
        { role: 'system', content: '你是专业的内容创作者' },
        { role: 'user', content: `写一篇关于"${topic}"的博客` },
      ],
    }
  );
  
  // 异步生成 SEO 友好的 slug 和摘要
  const summary = await c.env.AI.run(
    '@cf/meta/llama-3-8b-instruct',
    {
      messages: [
        { role: 'user', content: `总结以下内容(30 字内):${aiResponse.response}` },
      ],
    }
  );
  
  // 存储到 D1
  const slug = topic.toLowerCase().replace(/\s+/g, '-');
  await c.env.DB.prepare(`
    INSERT INTO posts (slug, title, content, summary, user_id)
    VALUES (?, ?, ?, ?, ?)
  `).bind(slug, topic, aiResponse.response, summary.response, c.get('jwtPayload').sub).run();
  
  return c.json({ success: true });
});

export default app;

完整架构:

┌─────────────────────────────────────────────────────────┐
│  Cloudflare 全球边缘网络(300+ 节点)                   │
├─────────────────────────────────────────────────────────┤
│  Workers (Hono)         │  D1 (SQLite)                │
│  - API 路由             │  - users                    │
│  - JWT 鉴权             │  - posts                    │
│  - Workers AI           │  - sessions                 │
│  - 缓存                 │                             │
│                          │                             │
│  KV (键值存储)           │  R2 (对象存储)              │
│  - 缓存                  │  - 用户头像                  │
│  - Session              │  - 文件附件                  │
│                          │                             │
│  Queues (异步任务)         │  Durable Objects            │
│  - 邮件发送              │  - WebSocket                │
│  - AI 处理              │  - 实时协作                  │
└─────────────────────────────────────────────────────────┘

这种架构:延迟 < 30ms、成本 < $10/月、可扩展到百万用户。

总结(深度版)

边缘计算已经从"实验性"走向"生产就绪",2026 年成为新项目首选:

核心优势

  • ✅ 全球延迟 < 30ms
  • ✅ 冷启动 < 5ms
  • ✅ 成本降低 10-100x
  • ✅ 零运维 / 自动扩容
  • ✅ AI 原生(Workers AI)

生态成熟度

  • ✅ Hono 框架:30k+ stars
  • ✅ Cloudflare Workers:300+ 节点
  • ✅ D1 + R2 + KV + Queues:完整生态
  • ✅ Durable Objects:状态管理

适用场景

  • CRUD API
  • AI 推理
  • 实时协作
  • IoT 数据处理
  • 全球 SaaS

不适用

  • 长任务(> 30 秒)
  • 大文件处理
  • 需要特定 OS

2026 年边缘计算已成事实标准。所有新项目都应该用边缘架构,老项目应该分阶段迁移。

立即行动

  1. 本周:用 Hono 创建一个 Workers 应用
  2. 本月:评估现有 API 迁移到边缘
  3. 本季:完整迁移一个项目到 Cloudflare
  4. 长期:所有新项目默认用边缘架构

边缘计算是后端架构的下一站,已经准备好了。

团队学习路径

第 1 周:Hono 基础

  • 理解 Web Standards(fetch / Request / Response)
  • 创建第一个 Hono 应用
  • 本地运行 + 部署到 Cloudflare

第 2 周:D1 + R2

  • 学习 D1 SQL 和 migrations
  • 使用 R2 存储文件
  • 理解边缘数据库限制

第 3 周:Workers AI

  • 调用 Llama-3 / BGE 模型
  • 实现流式响应
  • 端侧推理 + 缓存策略

第 4 周:Durable Objects + Queues

  • 实现 WebSocket 实时通信
  • 异步任务处理
  • 状态管理

持续学习

  • 关注 Cloudflare 博客
  • 试用新特性(如 Vectorize / Hyperdrive)
  • 参与 Hono 社区

行业应用案例

电商行业

  • 商品搜索(Workers AI 嵌入)
  • 推荐系统(边缘 KV)
  • 实时价格(D1 + Cache)

媒体行业

  • 内容分发(R2 边缘存储)
  • 图像处理(WASM)
  • 个性化推荐(AI)

金融行业

  • 风控规则(边缘 KV)
  • 实时行情(Durable Objects)
  • 支付路由(Workers)

SaaS 行业

  • 多租户 API(JWT + KV)
  • 实时协作(WebSocket)
  • 数据分析(Queues + D1)

与 AI 集成的最佳实践

// 边缘 AI 应用模式
class EdgeAIApp {
  // 1. 缓存 AI 结果
  async cachedInference(prompt: string) {
    const cacheKey = `ai:${hash(prompt)}`;
    const cached = await this.env.KV.get(cacheKey);
    if (cached) return JSON.parse(cached);
    
    const result = await this.env.AI.run(model, { prompt });
    await this.env.KV.put(cacheKey, JSON.stringify(result), {
      expirationTtl: 3600,
    });
    return result;
  }
  
  // 2. 流式响应
  async streamCompletion(messages: any[]) {
    return streamText(async (stream) => {
      const ai = await this.env.AI.run(model, {
        messages,
        stream: true,
      });
      for await (const chunk of ai) {
        await stream.write(chunk.response);
      }
    });
  }
  
  // 3. 嵌入 + 向量检索
  async semanticSearch(query: string) {
    const embedding = await this.env.AI.run(
      '@cf/baai/bge-base-en-v1.5',
      { text: [query] }
    );
    
    // 使用 Vectorize(Cloudflare 向量数据库)
    const matches = await this.env.VECTORIZE.query(
      embedding.data[0],
      { topK: 10 }
    );
    
    return matches;
  }
}

这些模式让边缘计算 + AI 成为 2026 年最强大的组合。

�� 同主题文章

⚙️ 后端 / 架构 分类更多