• 缓存管理器


    /*
    缓存管理器
    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;
      }
    }
    

      

  • 相关阅读:
    面试官:HashMap死循环形成的原因是什么?
    这几个IDEA高级调试技巧,用完就是香
    图示JVM工作原理
    写二进制,姿势一定要骚,省字段,省带宽,提效率...
    阿里大佬总结的40个多线程面试题,你能答上来几个?
    全网最全RabbitMQ总结,别再说你不会RabbitMQ
    .NETCore微服务探寻(三)
    .NETCore微服务探寻(二)
    .NETCore微服务探寻(一)
    谈谈spring-boot-starter-data-redis序列化
  • 原文地址:https://www.cnblogs.com/caoke/p/14789435.html
Copyright © 2020-2023  润新知