Nội dung bài họcLesson content
Edge computing là gì?What is edge computing?
Edge computing là chạy code tại các máy chủ gần user nhất (toàn cầu), thay vì 1 server trung tâm. Cloudflare Workers chạy code JavaScript trên 300+ location toàn cầu. Latency thấp (<50ms), tự động scale, không cần quản server. Lý tưởng cho API, redirect, A/B test.Edge computing is running code at servers closest to the user (globally), instead of 1 central server. Cloudflare Workers runs JavaScript code across 300+ global locations. Low latency (<50ms), auto-scaling, no server management. Ideal for APIs, redirects, A/B testing.
Tạo Worker đầu tiênCreating your first Worker
Worker là 1 file JavaScript export default object với method fetch. Mỗi request đến sẽ gọi fetch(request, env, ctx). Trả về Response. Cài wrangler: npm install -g wrangler. Tạo: wrangler generate my-worker. Deploy: wrangler deploy.A Worker is 1 JavaScript file exporting a default object with a fetch method. Each incoming request calls fetch(request, env, ctx). Returns a Response. Install wrangler: npm install -g wrangler. Create: wrangler generate my-worker. Deploy: wrangler deploy.
// src/index.js — Cloudflare Worker
export default {
async fetch(request, env) {
const url = new URL(request.url);
if (url.pathname === '/api/hello') {
return Response.json({
message: 'Xin chào từ Edge! / Hello from Edge!',
region: request.cf?.country ?? 'unknown',
timestamp: new Date().toISOString()
});
}
if (url.pathname === '/api/echo' && request.method === 'POST') {
const body = await request.json();
return Response.json({ you_sent: body });
}
return new Response('Not found', { status: 404 });
}
};
KV: Key-Value storageKV: Key-Value storage
KV (Workers KV) là database key-value toàn cầu, đọc nhanh. Lý tưởng cho config, session, cache. Tạo KV namespace trong wrangler.toml. Dùng env.KV_NAMESPACE.get(key) / put(key, value). Lưu ý: KV là eventually consistent — không dùng cho dữ liệu cần nhất quán ngay.KV (Workers KV) is a global key-value database with fast reads. Ideal for config, sessions, cache. Create a KV namespace in wrangler.toml. Use env.KV_NAMESPACE.get(key) / put(key, value). Note: KV is eventually consistent — don't use for data needing immediate consistency.
// wrangler.toml
# [[kv_namespaces]]
# binding = "MY_KV"
# id = "abc123..."
// src/index.js
export default {
async fetch(request, env) {
const url = new URL(request.url);
// Lưu giá trị
if (url.pathname === '/set') {
await env.MY_KV.put('greeting', 'Xin chào từ KV!');
return new Response('Đã lưu');
}
// Đọc giá trị
if (url.pathname === '/get') {
const value = await env.MY_KV.get('greeting');
return Response.json({ greeting: value });
}
return new Response('Not found', { status: 404 });
}
};
D1: SQL database trên EdgeD1: SQL database on the Edge
D1 là SQLite-based database của Cloudflare. ACID, SQL đầy đủ. Tạo: wrangler d1 create my-db. Bind trong wrangler.toml. Dùng env.DB.prepare(sql).bind(...).run/all/first. D1 phù hợp cho dữ liệu cần query phức tạp, transaction.D1 is Cloudflare's SQLite-based database. ACID, full SQL. Create: wrangler d1 create my-db. Bind in wrangler.toml. Use env.DB.prepare(sql).bind(...).run/all/first. D1 suits data needing complex queries, transactions.
// wrangler.toml
# [[d1_databases]]
# binding = "DB"
# database_name = "my-db"
# database_id = "abc123..."
// src/index.js
export default {
async fetch(request, env) {
const url = new URL(request.url);
if (url.pathname === '/users') {
const users = await env.DB.prepare(
'SELECT id, name, email FROM users ORDER BY name'
).all();
return Response.json({ users: users.results });
}
if (url.pathname === '/users' && request.method === 'POST') {
const { name, email } = await request.json();
await env.DB.prepare(
'INSERT INTO users (name, email) VALUES (?, ?)'
).bind(name, email).run();
return Response.json({ success: true }, { status: 201 });
}
return new Response('Not found', { status: 404 });
}
};