
CDN与边缘缓存指南
缓存控制头(Cache-Control Headers)
// 带内容哈希的静态资源(永久缓存)
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
// HTML页面(短TTL,需重新验证)
res.setHeader('Cache-Control', 'public, max-age=0, must-revalidate');
// 个性化API响应
res.setHeader('Cache-Control', 'private, no-store');
// CDN可缓存的API响应
res.setHeader('Cache-Control', 'public, s-maxage=300, max-age=60');
// s-maxage: CDN TTL(5分钟),max-age: 浏览器TTL(1分钟)
// 后台重新验证时提供过期内容
res.setHeader('Cache-Control', 'public, max-age=60, stale-while-revalidate=3600');

ETag与条件请求
app.get('/api/products', async (req, res) => {
const products = await productRepo.findAll();
const etag = crypto.createHash('md5').update(JSON.stringify(products)).digest('hex');
res.setHeader('ETag', `"${etag}"`);
if (req.headers['if-none-match'] === `"${etag}"`) {
return res.status(304).end(); // 未修改 - 节省带宽
}
res.json(products);
});

缓存失效(Cache Invalidation)
# Cloudflare:按URL清除
curl -X POST "https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/purge_cache" \
-H "Authorization: Bearer ${CF_TOKEN}" \
--data '{"files": ["https://example.com/api/products"]}'
# 按缓存标签清除(定向失效)
curl -X POST "..." --data '{"tags": ["products", "category:electronics"]}'
// 为响应打标签以便定向失效
app.get('/products/:id', async (req, res) => {
const product = await productRepo.findById(req.params.id);
res.setHeader('Cache-Tag', `product:${product.id}`);
res.setHeader('Cache-Control', 'public, s-maxage=3600');
res.json(product);
});
async function updateProduct(id: string, data: UpdateProductDto): Promise<void> {
await productRepo.update(id, data);
await cloudflare.purgeByTag([`product:${id}`]); // 即时失效
}

边缘函数(Cloudflare Workers)
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
const country = request.headers.get('CF-IPCountry') || 'US';
// 地理路由
if (country === 'DE') {
url.hostname = 'eu.api.example.com';
}
const response = await fetch(url.toString(), request);
const headers = new Headers(response.headers);
headers.set('X-Served-Country', country);
return new Response(response.body, { headers });
}
};
源站防护(Origin Shielding)
无防护:
100个CDN边缘节点 -> 全部未命中 -> 100个请求到达源站
有防护:
100个CDN边缘节点 -> 防护节点(单次未命中) -> 1个请求到达源站
减少源站流量90%以上
积极的边缘缓存是全球服务最高杠杆的性能优化手段。