边缘计算指南
边缘 vs 源站
| 边缘 | 源站服务器 | |
|---|---|---|
| 延迟 | <50ms 全球 | 100–500ms |
| 内存 | 128MB 典型 | GB级 |
| 运行时 | V8 isolates (JS/WASM) | Node/Go/Python/Java |
| 冷启动 | <5ms | 100ms–2s |
| 联网 | 有限(无原始TCP) | 完整 |
| 文件系统 | 无 | ✓ |
Cloudflare Workers示例
// Cloudflare Workers (runs in 200+ PoPs globally)
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url)
// A/B testing at the edge
if (url.pathname === '/') {
const variant = Math.random() < 0.5 ? 'A' : 'B'
const response = await fetch(`https://origin.example.com/?variant=${variant}`)
return new Response(response.body, {
headers: {
...Object.fromEntries(response.headers),
'X-AB-Variant': variant,
}
})
}
// KV store for caching
const cached = await env.MY_KV.get(url.pathname)
if (cached) return new Response(cached, { headers: { 'Content-Type': 'application/json' } })
const data = await fetch('https://api.example.com' + url.pathname).then(r => r.text())
await env.MY_KV.put(url.pathname, data, { expirationTtl: 3600 })
return new Response(data)
}
}
边缘数据库选项
| 产品 | 类型 | 适合 |
|---|---|---|
| Cloudflare KV | Key-Value | 配置、会话、缓存数据 |
| Cloudflare D1 | SQLite | 边缘关系型数据 |
| Turso | LibSQL/SQLite | 地理分布式SQLite |
| Upstash Redis | Redis | 限流、发布订阅 |
| Deno KV | Key-Value | Deno Deploy应用 |
| PlanetScale | MySQL | 分支、全球读取 |