文章目录
- 边缘数据库(Edge Database): 数据存储在CDN边缘节点(全球分布) 读写延迟 < 50ms(vs 中心化数据库 200-500ms) 自动同步(最终一致性) vs 中心化数据库: 中心化:所有请求到主库(延迟高) 边缘:就近读写(延迟低) 2026年趋势: 边缘数据库市场增长 300%(2025-2026) 主要玩家:Cloudflare D1、Fauna、Turso、Neon
- | 数据库 | 类型 | 延迟 | 免费额度 | 适用场景 | |--------|------|--------|----------|----------| | Cloudflare D1 | SQLite(边缘) | < 10ms | 5GB/月 | 小型应用 | | Fauna | NoSQL(文档) | < 50ms | 100MB | 中型应用 | | Turso | libSQL(SQLite分支) | < 20ms | 500MB | 边缘优先 | | Neon | PostgreS(无服务器) | < 100ms | 3GB | 中心化+边缘 |
- // src/index.ts export default { async fetch(request: Request, env: Env): Promise { // 写入数据 if (request.method === 'POST') { const { title, content } = await request.json(); const stmt = env.DB.prepare( 'INSERT INTO posts (title, content) VALUES (?, ?)' ); const result = await stmt.bind(title, content).run(); return Response.json({ success: true, id: result.meta.last_row_id, }); } // 读取数据 const { results } = await env.DB.prepare( 'SELECT * FROM posts ORDER BY created_at DESC LIMIT 10' ).all(); return Response.json(results); }, };
- # 部署 wrangler deploy
-
- 1. 访问 https://fauna.com/ 注册账号 创建数据库:my-edge-db 获取API Key(Security → Keys → New Key)
- npm install fauna
- // write-to-fauna.js const { Client, fql } = require('fauna'); const client = new Client({ secret: 'YOUR_FAUNA_SECRET', }); async function createPost(title, content) { const result = await client.query(fql` posts.create({ title: ${title}, content: ${content}, created_at: Time.now(), }) `); console.log('创建成功:', result); } createPost('边缘数据库实战', 'Fauna教程...');
- // read-from-fauna.js async function getPosts() { const result = await client.query(fql` posts.all() { title, content, created_at } `); console.log('文章列表:', result.data); } getPosts();
- // workers/fauna-worker.ts import { Client, fql } from 'fauna'; export default { async fetch(request: Request): Promise { const client = new Client({ secret: FAUNA_SECRET, }); // 读取文章 const result = await client.query(fql` posts.all().take(10) { title, content } `); return Response.json(result.data); }, };
- -- schema.sql CREATE TABLE posts ( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, content TEXT NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP ); # 执行Schema turso db shell my-edge-db < schema.sql
- // write-to-turso.js import { createClient } from '@libsql/client'; const client = createClient({ url: 'libsql://my-edge-db-region.turso.io', authToken: 'YOUR_TURSO_TOKEN', }); async function createPost(title, content) { await client.execute({ sql: 'INSERT INTO posts (title, content) VALUES (?, ?)', args: [title, content], }); console.log('创建成功'); } createPost('边缘数据库实战', 'Turso教程...');
- // workers/turso-worker.ts import { createClient } from '@libsql/client'; export default { async fetch(request: Request): Promise { const client = createClient({ url: 'libsql://my-edge-db-region.turso.io', authToken: TURSO_TOKEN, }); // 读取文章 const result = await client.execute({ sql: 'SELECT * FROM posts ORDER BY created_at DESC LIMIT 10', }); return Response.json(result.rows); }, };
- 架构: 中心:WordPress(MySQL)+ Rest API 边缘:Cloudflare D1(缓存层) 同步:Webhook(WordPress → D1) 流程: 用户请求 → Cloudflare Workers Workers查询D1(边缘缓存) 如果D1无数据 → 查询WordPress API → 写入D1 WordPress更新内容 → Webhook → 更新D1
- // WordPress插件:同步到D1 add_action('save_post', 'sync_to_d1'); function sync_to_d1($post_id) { $post = get_post($post_id); $data = [ 'id' => $post->ID, 'title' => $post->post_title, 'content' => $post->post_content, 'modified' => $post->post_modified, ]; // 调用Cloudflare Workers Webhook $response = wp_remote_post( 'https://my-worker.yourname.workers.dev/webhook', [ 'headers' => [ 'Content-Type' => 'application/json', ], 'body' => json_encode($data), ] ); } // workers/webhook.ts export default { async fetch(request: Request, env: Env): Promise { if (request.method !== 'POST') { return new Response('Method not allowed', { status: 405 }); } const data = await request.json(); // 同步到D1 await env.DB.prepare( `INSERT OR REPLACE INTO posts (id, title, content, modified) VALUES (?, ?, ?, ?)` ).bind( data.id, data.title, data.content, data.modified ).run(); return Response.json({ success: true }); }, };
- // workers/cached-d1.ts export default { async fetch(request: Request, env: Env): Promise { const cache = caches.default; let response = await cache.match(request); if (!response) { // 从D1读取 const { results } = await env.DB.prepare( 'SELECT * FROM posts LIMIT 10' ).all(); response = Response.json(results, { headers: { 'Cache-Control': 'max-age=300', // 缓存5分钟 }, }); // 存储到缓存 await cache.put(request, response.clone()); } return response; }, };
- // durable-objects/chat-room.ts export class ChatRoom { constructor(state: DurableObjectState) { this.state = state; this.sessions = new Map(); } async fetch(request: Request): Promise { // WebSocket连接(实时聊天) const webSocketPair = new WebSocketPair(); const [client, server] = Object.values(webSocketPair); server.accept(); // 存储消息到D1 server.addEventListener('message', async (event) => { const message = JSON.parse(event.data); await this.state.storage.put(`msg:${Date.now()}`, message); // 广播给所有客户端 this.sessions.forEach((session) => { session.send(JSON.stringify(message)); }); }); return new Response(null, { status: 101, webSocket: client, }); } }
本文详解2026年边缘数据库技术,包括Cloudflare D1、Fauna、Turso等实战。
边缘数据库(Edge Database):
- 数据存储在CDN边缘节点(全球分布)
- 读写延迟 < 50ms(vs 中心化数据库 200-500ms)
- 自动同步(最终一致性)
vs 中心化数据库:
- 中心化:所有请求到主库(延迟高)
- 边缘:就近读写(延迟低)
2026年趋势:
- 边缘数据库市场增长 300%(2025-2026)
- 主要玩家:Cloudflare D1、Fauna、Turso、Neon
| 数据库 | 类型 | 延迟 | 免费额度 | 适用场景 |
|--------|------|--------|----------|----------|
| Cloudflare D1 | SQLite(边缘) | < 10ms | 5GB/月 | 小型应用 |
| Fauna | NoSQL(文档) | < 50ms | 100MB | 中型应用 |
| Turso | libSQL(SQLite分支) | < 20ms | 500MB | 边缘优先 |
| Neon | PostgreS(无服务器) | < 100ms | 3GB | 中心化+边缘 |
# 安装Wrangler(Cloudflare CLI)
npm install -g wrangler
wrangler login
wrangler whoami
# 创建数据库
wrangler d1 create my-edge-db
-- schema.sql
CREATE TABLE posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
content TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_created_at ON posts(created_at DESC);
# 执行Schema(本地)
wrangler d1 execute my-edge-db --local --file=./schema.sql
wrangler d1 execute my-edge-db --remote --file=./schema.sql
// src/index.ts
export default {
async fetch(request: Request, env: Env): Promise {
// 写入数据
if (request.method === 'POST') {
const { title, content } = await request.json();
const stmt = env.DB.prepare(
'INSERT INTO posts (title, content) VALUES (?, ?)'
);
const result = await stmt.bind(title, content).run();
return Response.json({
success: true,
id: result.meta.last_row_id,
});
}
// 读取数据
const { results } = await env.DB.prepare(
'SELECT * FROM posts ORDER BY created_at DESC LIMIT 10'
).all();
return Response.json(results);
},
};
# 部署
wrangler deploy
1. 访问 https://fauna.com/
- 注册账号
- 创建数据库:my-edge-db
- 获取API Key(Security → Keys → New Key)
npm install fauna
// write-to-fauna.js
const { Client, fql } = require('fauna');
const client = new Client({
secret: 'YOUR_FAUNA_SECRET',
});
async function createPost(title, content) {
const result = await client.query(fql`
posts.create({
title: ${title},
content: ${content},
created_at: Time.now(),
})
`);
console.log('创建成功:', result);
}
createPost('边缘数据库实战', 'Fauna教程...');
// read-from-fauna.js
async function getPosts() {
const result = await client.query(fql`
posts.all() {
title,
content,
created_at
}
`);
console.log('文章列表:', result.data);
}
getPosts();
// workers/fauna-worker.ts
import { Client, fql } from 'fauna';
export default {
async fetch(request: Request): Promise {
const client = new Client({
secret: FAUNA_SECRET,
});
// 读取文章
const result = await client.query(fql`
posts.all().take(10) {
title,
content
}
`);
return Response.json(result.data);
},
};
# Linux/macOS
curl -sSf https://get.tur.so/install.sh | bash
irm https://get.tur.so/install.ps1 | iex
turso --version
# 登录
turso auth login
turso db create my-edge-db
turso db show my-edge-db
-- schema.sql
CREATE TABLE posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
content TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
# 执行Schema
turso db shell my-edge-db < schema.sql
// write-to-turso.js
import { createClient } from '@libsql/client';
const client = createClient({
url: 'libsql://my-edge-db-region.turso.io',
authToken: 'YOUR_TURSO_TOKEN',
});
async function createPost(title, content) {
await client.execute({
sql: 'INSERT INTO posts (title, content) VALUES (?, ?)',
args: [title, content],
});
console.log('创建成功');
}
createPost('边缘数据库实战', 'Turso教程...');
// workers/turso-worker.ts
import { createClient } from '@libsql/client';
export default {
async fetch(request: Request): Promise {
const client = createClient({
url: 'libsql://my-edge-db-region.turso.io',
authToken: TURSO_TOKEN,
});
// 读取文章
const result = await client.execute({
sql: 'SELECT * FROM posts ORDER BY created_at DESC LIMIT 10',
});
return Response.json(result.rows);
},
};
架构:
- 中心:WordPress(MySQL)+ Rest API
- 边缘:Cloudflare D1(缓存层)
- 同步:Webhook(WordPress → D1)
流程:
- 用户请求 → Cloudflare Workers
- Workers查询D1(边缘缓存)
- 如果D1无数据 → 查询WordPress API → 写入D1
- WordPress更新内容 → Webhook → 更新D1
// WordPress插件:同步到D1
add_action('save_post', 'sync_to_d1');
function sync_to_d1($post_id) {
$post = get_post($post_id);
$data = [
'id' => $post->ID,
'title' => $post->post_title,
'content' => $post->post_content,
'modified' => $post->post_modified,
];
// 调用Cloudflare Workers Webhook
$response = wp_remote_post(
'https://my-worker.yourname.workers.dev/webhook',
[
'headers' => [
'Content-Type' => 'application/json',
],
'body' => json_encode($data),
]
);
}
// workers/webhook.ts
export default {
async fetch(request: Request, env: Env): Promise {
if (request.method !== 'POST') {
return new Response('Method not allowed', { status: 405 });
}
const data = await request.json();
// 同步到D1
await env.DB.prepare(
`INSERT OR REPLACE INTO posts (id, title, content, modified)
VALUES (?, ?, ?, ?)`
).bind(
data.id,
data.title,
data.content,
data.modified
).run();
return Response.json({ success: true });
},
};
// workers/cached-d1.ts
export default {
async fetch(request: Request, env: Env): Promise {
const cache = caches.default;
let response = await cache.match(request);
if (!response) {
// 从D1读取
const { results } = await env.DB.prepare(
'SELECT * FROM posts LIMIT 10'
).all();
response = Response.json(results, {
headers: {
'Cache-Control': 'max-age=300', // 缓存5分钟
},
});
// 存储到缓存
await cache.put(request, response.clone());
}
return response;
},
};
// durable-objects/chat-room.ts
export class ChatRoom {
constructor(state: DurableObjectState) {
this.state = state;
this.sessions = new Map();
}
async fetch(request: Request): Promise {
// WebSocket连接(实时聊天)
const webSocketPair = new WebSocketPair();
const [client, server] = Object.values(webSocketPair);
server.accept();
// 存储消息到D1
server.addEventListener('message', async (event) => {
const message = JSON.parse(event.data);
await this.state.storage.put(`msg:${Date.now()}`, message);
// 广播给所有客户端
this.sessions.forEach((session) => {
session.send(JSON.stringify(message));
});
});
return new Response(null, {
status: 101,
webSocket: client,
});
}
}
| 场景 | 推荐数据库 | 理由 |
|------|------------|------|
| 小型应用(< 5GB) | Cloudflare D1 | 便宜(免费5GB) |
| 中型应用(需要复杂查询) | Fauna | NoSQL灵活 |
| 边缘优先(SQLite兼容) | Turso | libSQL性能强 |
| 中心化+边缘(PostgreS兼容) | Neon | SQL标准 |
边缘数据库是2026年最前沿的技术。读写延迟 < 50ms,极大提升用户体验。
立即行动:用Cloudflare D1创建你的第一个边缘数据库!

评论(0)