zoukankan      html  css  js  c++  java
  • 中间件-缓存加载函数

    /*
    缓存加载函数
    cacheLen:最多缓存多少个接口
    id:唯一值
    name:方法名
    syncFunc:加载函数
     */
    // 缓存最近的20个接口
    const methodCacheArr = []
    let cacheLen = 20
    try {
      const arr=JSON.parse(localStorage.getItem('queryNoError'))
      arr.forEach(function (item) {
        methodCacheArr.push(item)
      })
      cacheLen=arr.length+20;
    }catch (e) {
      
    }
    
    function getCacheIndex (val, key) {
      let has = -1
      for (let i = methodCacheArr.length - 1; i >= 0; i--) {
        if (val === methodCacheArr[i][key]) {
          has = i
          break
        }
      }
      return has
    }
    
    export function getCache (name) {
      const has = getCacheIndex(name, 'name')
      if (has > -1) {
        return methodCacheArr[has].res
      } else {
        return null
      }
    }
    
    export function delCache (name) {
      const has = getCacheIndex(name, 'name')
      if (has > -1) {
        methodCacheArr.splice(has, 1)
      }
    }
    
    export async function limitCache ({id, name, useCache,queryNoError}, syncFunc) {
      const has = getCacheIndex(id, 'id')
    
      if (useCache && has > -1) {
        if(typeof useCache !== 'number'){
          useCache=300;
        }
        if (useCache * 1000 + methodCacheArr[has].time > +new Date()) {
          return methodCacheArr[has].res
        }
      }
      let res = await syncFunc()
      //更新缓存
      if (res && res.flag === 'S') {
        if (has > -1) {
          methodCacheArr.splice(has, 1)
        }
        methodCacheArr.push({
          id: id,
          queryNoError:queryNoError,
          name: name,
          time: +new Date(),
          res: res
        })
        if (methodCacheArr.length > cacheLen) {
          methodCacheArr.splice(0, 1)
        }
        if(queryNoError){
          const arr=methodCacheArr.filter(function (item) {
            return item.queryNoError;
          })
          if (arr.length > 20) {
            arr.splice(0, 1)
          }
          localStorage.setItem('queryNoError',JSON.stringify(arr))
        }
      }else if(has > -1&&queryNoError){
        //兼容查询失败的情况
        return methodCacheArr[has].res;
      }
      return res
    }
    

      

  • 相关阅读:
    jvm 垃圾收集算法
    jvm 判断对象死亡
    jvm 内存分配
    jvm 对象奥秘
    mysql事务测试及delete和update是使用行级锁,还是表级锁
    sql语句中where后边的哪些条件会使索引失效 -- SQL语句优化
    java nio详解
    mysql数据库优化概述详解
    java 序列化和反序列化
    java io框架详解
  • 原文地址:https://www.cnblogs.com/caoke/p/14000416.html
Copyright © 2011-2022 走看看