js实现简单的缓存管理

100 阅读1分钟
/**
 * 缓存帮助类
 */
class CacheHelper {
  store = {}

  /**
   * 获取缓存
   * @param {*} key 缓存key
   * @returns 缓存结果(可能为null)
   */
  getCache(key) {
    const cache = this.store[key]
    if (!cache) {
      return null
    }
    const curTime = new Date().getTime()
    if (curTime > cache.expireTime) {
      // 删除已过期的缓存
      this.removeCache(key)
      return null
    }
    return cache.value
  }

  /**
   * 删除缓存
   * @param {*} key 缓存key
   */
  removeCache(key) {
    delete this.store[key]
  }

  /**
   *
   * @param {*} key 缓存key
   * @param {*} value 缓存值
   * @param {*} time 缓存时间(单位:毫秒). 默认: 10分钟
   */
  setCache(key, value, time = 1000 * 60 * 10) {
    this.store[key] = {
      value,
      expireTime: new Date().getTime() + time,
    }
  }

  /**
   * 将一个返回Promise结果的函数,支持结果缓存
   * @param {*} fn 待包装的返回Promise的方法
   * @param {*} keyBuilder 缓存key构建方法(可以是字符串,也可以是一个函数)
   * @param {*} time 缓存时间(单位:毫秒). 默认:10分钟
   * @returns 返回包装后的方法
   */
  promiseGlobalCacheWrapper(fn, keyBuilder, time = 1000 * 60 * 10) {
    let that = this
    return async function (...args) {
      const key = typeof keyBuilder === 'string' ? keyBuilder : keyBuilder(...args)
      let cacheValue = that.getCache(key)
      console.log('是否找到缓存', cacheValue)
      if (!cacheValue) {
        fn.bind(this, ...args)
        cacheValue = await fn(...args)
        if (cacheValue) {
          that.setCache(key, cacheValue, time)
        }
      }
      return cacheValue
    }
  }
}
function sleep(time) {
  return new Promise(reslove => {
    setTimeout(() => {
      reslove()
    }, time)
  })
}

const cacheHelper = new CacheHelper()

async function test(p) {
  return new Promise(reslove => {
    setTimeout(() => {
      console.log('test:', p)
      reslove({ p })
    }, 1000)
  })
}
const testWrapper = cacheHelper.promiseGlobalCacheWrapper(test, 'hello', 1000 * 2)
const testWrapper2 = cacheHelper.promiseGlobalCacheWrapper(test, p => `demo:${p}`, 1000 * 2)
;(async () => {
  console.log('testWrapper:', 1)
  await testWrapper(10) // 无缓存
  console.log('testWrapper:', 2)
  await testWrapper(10) // 有缓存
  console.log('testWrapper:', 3)
  await testWrapper(10) // 有缓存
  await sleep(3000)
  console.log('testWrapper:', 4)
  await testWrapper(10) // 无缓存

  console.log('testWrapper2:', 1)
  await testWrapper2(10) // 无缓存
  console.log('testWrapper2:', 2)
  await testWrapper2(10) // 有缓存
  console.log('testWrapper2:', 3)
  await testWrapper2(10) // 有缓存
  await sleep(3000)
  console.log('testWrapper2:', 4)
  await testWrapper2(10) // 无缓存

  console.log('testWrapper2:', 5)
  await testWrapper2(9) // 无缓存
})()