跳到主要内容

缓存策略技术详解

概述

缓存策略是前端性能优化的核心技术,通过合理利用各种缓存机制来减少网络请求、提升资源加载速度、改善用户体验。

缓存原理

缓存层次结构

缓存层次结构图
┌─────────────────────────────────────────────────────────────┐
│ 用户浏览器 │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ 内存缓存 │ │ 磁盘缓存 │ │ 应用缓存 │ │
│ │ (最快) │ │ (较快) │ │ (中等) │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
└─────────────────────────────────────────────────────────────┘

HTTP缓存策略

强缓存(Cache-Control)

// Express.js示例
app.use('/static', express.static('public', {
maxAge: '1y', // 缓存1年
immutable: true, // 不可变资源
etag: false, // 禁用ETag
lastModified: false // 禁用Last-Modified
}));

协商缓存(ETag + Last-Modified)

// 协商缓存中间件
function conditionalCache(req, res, next) {
const filePath = path.join(__dirname, 'public', req.path);

if (!fs.existsSync(filePath)) {
return next();
}

const stats = fs.statSync(filePath);
const content = fs.readFileSync(filePath);
const etag = generateETag(content);
const lastModified = stats.mtime.toUTCString();

res.set({
'ETag': etag,
'Last-Modified': lastModified,
'Cache-Control': 'no-cache'
});

if (req.headers['if-none-match'] === etag) {
return res.status(304).end();
}

res.sendFile(filePath);
}

Service Worker缓存

基础Service Worker

// service-worker.js
const CACHE_NAME = 'app-cache-v1';
const STATIC_CACHE = 'static-cache-v1';

const STATIC_ASSETS = [
'/',
'/index.html',
'/css/main.css',
'/js/app.js'
];

self.addEventListener('install', event => {
event.waitUntil(
caches.open(STATIC_CACHE)
.then(cache => {
return cache.addAll(STATIC_ASSETS);
})
.then(() => self.skipWaiting())
);
});

self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(response => {
return response || fetch(event.request);
})
);
});

浏览器缓存

localStorage缓存

class LocalStorageCache {
constructor(prefix = 'cache_') {
this.prefix = prefix;
this.defaultTTL = 3600000; // 默认1小时
}

set(key, value, ttl = this.defaultTTL) {
try {
const cacheItem = {
value,
timestamp: Date.now(),
ttl
};

localStorage.setItem(this.prefix + key, JSON.stringify(cacheItem));
return true;
} catch (error) {
console.error('设置缓存失败:', error);
return false;
}
}

get(key) {
try {
const cached = localStorage.getItem(this.prefix + key);
if (!cached) return null;

const cacheItem = JSON.parse(cached);
const now = Date.now();

if (now - cacheItem.timestamp > cacheItem.ttl) {
this.remove(key);
return null;
}

return cacheItem.value;
} catch (error) {
return null;
}
}
}

最佳实践

1. 缓存策略选择

  • 静态资源: 强缓存 + 版本控制
  • 动态内容: 协商缓存 + 短期缓存
  • 用户数据: 私有缓存 + 认证相关

2. 缓存优化

  • 合理设置缓存时间
  • 实现缓存预热
  • 智能缓存失效
  • 监控缓存效果

通过合理的缓存策略,可以显著提升应用性能,减少网络请求,改善用户体验。