缓存管理器

/*
缓存管理器
cacheLen:最多缓存多少个数据
id:唯一值
name:方法名
syncFunc:加载函数
 */
class cacheManage {
  //cacheLen:最多缓存多少个数据
  constructor(cacheLen){
    this.cacheLen=cacheLen||20;
    this.cacheData=[];
  }
  //查询数据
  getCacheIndex (val, key) {
    let has = -1
    for (let i = this.cacheData.length - 1; i >= 0; i--) {
      if (val === this.cacheData[i][key]) {
        has = i
        break
      }
    }
    return has
  }
  /**option:
   * id:数据的唯一标识
   * cacheTime:请求前,数据在缓存时间内,则返回缓存数据
   * errTime:请求失败后,数据是否在缓存时间内,则返回缓存数据
   * */
  async getCacheSync(option,syncFunc){
    const id=option.id
    const cacheTime=option.cacheTime&&typeof option.cacheTime !== 'number'?300:option.cacheTime
    const errTime=option.errTime&&typeof option.errTime !== 'number'?300:option.errTime;

    const has =this.getCacheIndex(id, 'id')
    const cacheData=this.cacheData
    if(has > -1&&cacheTime&&cacheTime * 1000 + cacheData[has].time > +new Date()){
      return cacheData[has].data;
    }
    try {
      const data=await syncFunc()
      if (has > -1) {
        cacheData.splice(has, 1)
      }else if (cacheData.length > this.cacheLen) {
        cacheData.splice(0, 1)
      }
      cacheData.push({
        id: id,
        time: +new Date(),
        data: data
      })
      return data;
    }catch (e) {
      //兼容查询失败的情况
      if(has > -1&&errTime&&errTime * 1000 + cacheData[has].time > +new Date()){
        return cacheData[has].data;
      }
      throw e;
    }
  }
  /**option:
   * id:数据的唯一标识
   * */
  getCache(option,func){
    const id=option.id

    const has =this.getCacheIndex(id, 'id')
    const cacheData=this.cacheData
    if(has>-1){
      return cacheData[has].data;
    }
    const data= func();
    if (cacheData.length > this.cacheLen) {
      cacheData.splice(0, 1)
    }
    cacheData.push({
      id: id,
      data: data
    })
    return data;
  }
}

  

原文地址:https://www.cnblogs.com/caoke/p/14789435.html