接口缓存
简单版本,不考虑并发请求,只考虑单个请求的缓存。
js
class CacheRequest {
constructor() {
this.cache = new Map();
}
request ({url, params}) {
const cacheKey = `${url}?${JSON.stringify(params)}`;
// 如果缓存中存在,则直接返回缓存结果
if (this.cache.has(cacheKey)) {
console.log('从缓存中获取数据');
return Promise.resolve(this.cache.get(cacheKey));
}
// 如果缓存中不存在,则发起请求
return new Promise((resolve, reject) => {
// 模拟发起请求,3s后成功
setTimeout(() => {
const res = {
data: `Response from ${url} with params ${JSON.stringify(params)}`
};
this.cache.set(cacheKey, res); // 将结果存入缓存
resolve(res)
}, 3000)
});
}
}
// 测试
const cacheRequest1 = new CacheRequest();
cacheRequest1.request({url: '/api/data', params: {id: 1}})
.then(res => {
console.log(res);
// 输出: Response from /api/data with params {"id":1}
});
// 间隔5s后再发起请求
cacheRequest1.request({url: '/api/data', params: {id: 1}})
.then(res => {
console.log(res);
// 输出: Response from /api/data with params {"id":1}
});
复杂版本,考虑并发请求,并发请求只会发起一次,其他的请求会等待第一个请求返回结果。
js
class CacheRequest {
constructor() {
this.cache = new Map();
this.pendingRequests = new Map(); // 存储正在进行的请求
}
request({url, params}) {
const cacheKey = `${url}?${JSON.stringify(params)}`;
// 如果缓存中存在,则直接返回缓存结果
if (this.cache.has(cacheKey)) {
console.log('从缓存中获取数据');
return Promise.resolve(this.cache.get(cacheKey));
}
// 如果有正在进行的请求,则等待该请求完成
if (this.pendingRequests.has(cacheKey)) {
console.log('等待已有请求完成');
return this.pendingRequests.get(cacheKey);
}
// 如果没有正在进行的请求,则发起新的请求
const requestPromise = new Promise((resolve, reject) => {
// 模拟发起请求,3s后成功
setTimeout(() => {
const res = {
data: `Response from ${url} with params ${JSON.stringify(params)}`
};
this.cache.set(cacheKey, res); // 将结果存入缓存
this.pendingRequests.delete(cacheKey); // 请求完成后删除记录
resolve(res);
}, 3000);
});
// 将当前请求添加到正在进行的请求列表中
this.pendingRequests.set(cacheKey, requestPromise);
return requestPromise;
}
}
// 测试
const cacheRequest1 = new CacheRequest();
cacheRequest1.request({url: '/api/data', params: {id: 1}})
.then(res => {
console.log(res);
// 输出: Response from /api/data with params {"id":1}
});
// 间隔1s后再发起请求
cacheRequest1.request({url: '/api/data', params: {id: 1}})
.then(res => {
console.log(res);
// 输出: Response from /api/data with params {"id":1}
});
// 间隔5s后再发起请求
cacheRequest1.request({url: '/api/data', params: {id: 1}})
.then(res => {
console.log(res);
// 输出: Response from /api/data with params {"id":1}
});