HTTP 缓存高级策略:Cache-Control、ETag、stale-while-revalidate 与一致性技术背景合理的 HTTP 缓存策略能显著降低时延与服务器压力。通过强缓存(`max-age`/`immutable`)、协商缓存(`ETag`/`Last-Modified`)以及 `stale-while-revalidate` 后台刷新,可实现高命中率与一致性保障。核心内容前端请求与缓存控制async function fetchWithSWR(url: string) { const res = await fetch(url, { cache: 'force-cache' }); const cached = res.ok ? await res.clone().json().catch(() => null) : null; // 后台刷新 fetch(url, { cache: 'reload' }) .then(n => n.ok ? n.json() : null) .then(data => data && updateUI(data)) .catch(() => {}); return cached; } 服务端/边缘缓存头配置# 静态资源(版本化文件): Cache-Control: public, max-age=31536000, immutable # HTML(可缓存+SWR): Cache-Control: public, max-age=60, stale-while-revalidate=600 # API(协商缓存): ETag: "sha256:abc123" Cache-Control: private, max-age=0, must-revalidate 协商缓存流程(Node/Express 示例)import crypto from 'crypto'; import express from 'express'; const app = express(); app.get('/api/data', (req, res) => { const payload = JSON.stringify({ updatedAt: Date.now(), items: [1,2,3] }); const etag = 'W/"' + crypto.createHash('sha256').update(payload).digest('hex') + '"'; if (req.headers['if-none-match'] === etag) { res.status(304).end(); return; } res.setHeader('ETag', etag); res.setHeader('Cache-Control', 'private, max-age=0, must-revalidate'); res.type('application/json').send(payload); }); 版本与一致性校验(前端)async function checkVersionAndReload(manifestUrl = '/version.json') { const local = sessionStorage.getItem('app-version'); const res = await fetch(manifestUrl, { cache: 'no-cache' }); const { version } = await res.json(); if (local && local !== version) { // 版本发生变化,清理缓存并强制刷新关键资源 if ('caches' in window) { const keys = await caches.keys(); await Promise.all(keys.map(k => caches.delete(k))); } location.reload(); } else { sessionStorage.setItem('app-version', version); } } 技术验证参数在 Cloudflare CDN + 源站(Chrome 128/Edge 130,全球流量)下:静态资源缓存命中率:≥ 90%HTML SWR 生效覆盖率:≥ 85%API 304 响应占比:≥ 40%首屏 TTFB:下降 25–45%应用场景版本化静态资源的长效缓存与极致加载性能动态页面的近实时刷新与就近渲染协同API 数据一致性保障与带宽成本优化最佳实践对静态资源启用指纹与 `immutable`,避免误刷新HTML 使用 SWR,兼顾实时性与性能API 启用 ETag/Last-Modified,配合 304 降本增效建立版本校验与缓存清理机制,确保一致性

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部