浏览器直接使用本地缓存,不与服务器通信。
控制头部:
Cache-Control: max-age=31536000
Cache-Control: no-cache
Cache-Control: no-store
Cache-Control: must-revalidate
Expires: Wed, 12 Jun 2026 12:00:00 GMT
特点:
200 (from disk cache)
或 200 (from memory cache)
浏览器与服务器协商验证资源是否更新。
控制头部:
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"
If-None-Match: "33a64df551425fcc55e4d42a148795d9f25f89d4"
Last-Modified: Wed, 12 Jun 2024 12:00:00 GMT
If-Modified-Since: Wed, 12 Jun 2024 12:00:00 GMT
特点:
Cache Storage API 是现代浏览器提供的可编程缓存接口。
使用场景:
访问限制:
控制台访问:
// 打开缓存
const cache = await caches.open('v1');
// 存储响应
await cache.put('/api/data', response);
// 读取缓存
const cached = await cache.match('/api/data');
// 删除缓存
await cache.delete('/api/data');
// 清理所有缓存
const keys = await caches.keys();
await Promise.all(keys.map(key => caches.delete(key)));
module.exports = {
output: {
filename: '[name].[contenthash:8].js',
chunkFilename: '[name].[contenthash:8].chunk.js',
clean: true // 清理 dist 目录
},
optimization: {
moduleIds: 'deterministic', // 确保模块 ID 稳定
runtimeChunk: 'single', // 分离 runtime 代码
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
}
}
}
}
# HTML - 协商缓存
location / {
try_files $uri $uri/ /index.html;
add_header Cache-Control "no-cache";
etag on;
}
# 静态资源 - 长期缓存
location /static/ {
add_header Cache-Control "public, max-age=31536000, immutable";
}
# 动态 chunks - 长期缓存
location /chunks/ {
add_header Cache-Control "public, max-age=31536000, immutable";
}
// webpack 注入版本信息
new webpack.DefinePlugin({
'process.env.APP_VERSION': JSON.stringify(require('./package.json').version),
'process.env.BUILD_TIME': JSON.stringify(new Date().toISOString())
})
class VersionManager {
async checkUpdate() {
const response = await fetch('/version.json', {
headers: { 'Cache-Control': 'no-cache' }
});
const { version, buildTime } = await response.json();
if (version !== process.env.APP_VERSION ||
buildTime !== process.env.BUILD_TIME) {
await this.handleUpdate();
}
}
async handleUpdate() {
await this.clearCaches();
if (confirm('发现新版本,是否刷新?')) {
window.location.reload(true);
}
}
}
#!/bin/bash
VERSION=$(date +%Y%m%d%H%M%S)
DEPLOY_DIR="/usr/share/nginx/html"
# 1. 新建版本目录
mkdir -p ${DEPLOY_DIR}/${VERSION}
# 2. 部署新文件
cp -r dist/* ${DEPLOY_DIR}/${VERSION}/
# 3. 切换版本
ln -sfn ${DEPLOY_DIR}/${VERSION} ${DEPLOY_DIR}/current
# 4. 保留最近版本
ls -dt ${DEPLOY_DIR}/20* | tail -n +4 | xargs rm -rf
# 开发环境配置
location / {
add_header Cache-Control "no-store";
add_header Pragma no-cache;
}
特点:
# 测试环境配置
location / {
add_header Cache-Control "no-cache";
etag on;
if_modified_since exact;
}
特点:
策略:
症状:
解决方案:
症状:
解决方案:
症状:
解决方案:
记住:缓存策略不仅是技术选择,更是产品需求、用户体验和运维效率的平衡。好的缓存策略应该: