// 一个多级缓存的实际应用
class MultiLevelCache {
constructor() {
this.memoryCache = new Map(); // 1级缓存:最快
this.cacheName = 'api-cache-v1'; // 2级缓存:Cache API
}
async getData(url) {
// 1. 检查内存缓存
if (this.memoryCache.has(url)) {
console.log('从内存缓存获取');
return this.memoryCache.get(url);
}
// 2. 检查 Cache API
const cache = await caches.open(this.cacheName);
const cachedResponse = await cache.match(url);
if (cachedResponse) {
const data = await cachedResponse.json();
// 存入内存缓存
this.memoryCache.set(url, data);
console.log('从Cache API获取');
return data;
}
// 3. 发起网络请求
const response = await fetch(url);
const data = await response.json();
// 4. 存储到各级缓存
this.memoryCache.set(url, data);
cache.put(url, new Response(JSON.stringify(data)));
console.log('从网络获取');
return data;
}
}
// 使用
const cache = new MultiLevelCache();
cache.getData('/api/users'); // 第一次:网络
cache.getData('/api/users'); // 第二次:内存