zoukankan      html  css  js  c++  java
  • 缓存管理器

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

      

  • 相关阅读:
    递归删除文件夹及文件的方法
    12个国外优秀.Net开源项目
    ASP.NET刷新页面的六种方法
    C#实现多语言界面程序
    HyperLink 传参数要使传递的参数为字符串
    实现本地化多语言
    安卓开发学习
    Ajax异步处理当用户申请新用户
    3D MAX 介绍
    Ajax 用户登录验证
  • 原文地址:https://www.cnblogs.com/caoke/p/14789435.html
Copyright © 2011-2022 走看看