这里说的http缓存是指在前端同时发起很多api和参数都相同的get请求,特别是在map for 循环里,一个组件被循环多次,它里面的接口也会多次重复请求,那么在短时间内多次发重复请求 肯定是性能不友好的,所以我做了一个缓存,代码如下
/**做得默认6s缓存 */
class CacheHttp {
time = 6 * 1000;
retPromiseMap = new Map();
http(api, param, httpInstance) {
const key = getHash(api + JSON.stringify(param));
const cacheData = this.retPromiseMap.get(key);
const setPromise = () => {
//发出真实的http请求,缓存promise 用map储存 下一次用
let ret = httpInstance(api, param);
const temp = {
startTime: new Date().getTime(),
retPromise: ret,
isFinish: false, //记录promise是否已经是完成状态了 如果是完成状态 就要重新发请求
};
ret &&
ret.finally(() => {
temp.isFinish = true;
});
this.retPromiseMap.set(key, temp);
return ret;
};
//说明还没有缓存过
if (!cacheData) {
return setPromise();
}
if (new Date().getTime() - cacheData.startTime <= this.time && cacheData.isFinish === false) {
console.log('http缓存发生作用');
return cacheData.retPromise;
} else {
//说明缓存过期了
return setPromise();
}
}
}
function getHash(str) {
var hash = 0,
i,
chr;
if (str.length === 0) return hash;
for (i = 0; i < str.length; i++) {
chr = str.charCodeAt(i);
hash = (hash << 5) - hash + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
}
下面是使用举例
const cacheHttp = new CacheHttp();
cacheHttp.http(Apis.findSubNavList, { current: 1, pageSize: 1000, ...param }, httpGet).then((res) => {
});
网友评论