美文网首页
公共数据缓存

公共数据缓存

作者: 奋斗的小小小兔子 | 来源:发表于2020-08-26 18:28 被阅读0次

公共数据缓存调用

工具方法:

新建一个类,全局一个实例,暴露方法:getCacheDataByKey

  • 1 先判断传过来的keyList 是否在可支持列表中
  • 2 判断是否有缓存值,如果没有缓存直接进入第3步,如果有缓存,筛选中未缓存的key
  • 3 根据key,选择相应的策略,调用相应的接口,更新缓存
  • 4 从缓存中取keyList 需要的所有值

优势:进入下个页面,无需调用接口,刷新后,可重新调用接口

特殊说明:

  • 传过来的参数key,可以是单个str,或者 字符串列表,可以避免每个key都需要跑一遍函数
  • 缓存 cache 是个对象
  • 最终取值是从cache中取,返回给调用方的是 对象
import * as service from './service';

export const commonDataKeys = {
  OWNED_GROUP_DATA: 'ownedGroupData',
  APPLICATION_LIST: 'applicationList',
};

export class CommonDataCacheProxy {
  constructor() {
    this.cache = {};
  }

  /**
   * 检查请求的数据列表是否可用
   * @param reqKeyList {string | string[]}  请求的公共数据的Key值列表
   * @returns {string[]}                    可用的公共数据的Key值列表
   */
  checkReqKeyList = (reqKeyList) => {
    if (!Array.isArray(reqKeyList) && typeof reqKeyList === 'string') reqKeyList = [reqKeyList];
    if (!Array.isArray(reqKeyList)) throw new TypeError('参数reqKeyList不为Array或String');
    const invalidateKey = reqKeyList.find((key) => Object.values(commonDataKeys).every((itm) => itm !== key));
    if (invalidateKey) throw new Error(`不存在的commonDataKey: ${invalidateKey}`);
    return reqKeyList;
  }

  /**
   * 筛选出未缓存的Key值列表
   * @param reqKeyList  {string[]}  请求公共数据Key值列表
   * @returns {string[]}            未缓存的公共数据Key值列表
   */
  filterUncachedKeyList = (reqKeyList) => {
    const { cache } = this;
    if (Object.keys(cache).length === 0) return reqKeyList;
    return reqKeyList.filter((key) => !(cache[key] && cache[key].length > 0));
  };

  /**
   * 从缓存中取出请求的公共数据
   * @param reqKeyList  {string[]}  请求公共数据Key值列表
   * @returns {Object}  返回的公共数据
   */
  extractCachedCommonData = (reqKeyList) => {
    const { cache } = this;
    return reqKeyList.reduce((acc, key) => {
      acc[key] = cache[key]
      return acc;
    }, {});
  };

  fetchDataPromise = (key) => {
    const plan = {
      [commonDataKeys.OWNED_GROUP_DATA]: () => (
        service.loadOwnedGroupList().then(({ data }) => ({
          [commonDataKeys.OWNED_GROUP_DATA]: [data],
        }))
      ),
      [commonDataKeys.APPLICATION_LIST]: () => (
        service.loadApplicationList().then(({ data }) => {
          const format = (list) => list?.map((application) => (
            {
              label: application,
              value: application,
            }
          ));
          return {
            [commonDataKeys.APPLICATION_LIST]: format(data),
          };
        })
      ),
    };
    return plan[key]();
  }

  /**
   * 从服务端请求未缓存的公共数据
   * @param uncachedKeyList   {string[]}  待请求的公共数据的Key值列表
   */
  requestUncachedData = async (uncachedKeyList) => {
    const fetchDataList = await Promise.all(uncachedKeyList.map((reqKey) => (this.fetchDataPromise(reqKey))));
    const fetchDataMap = fetchDataList.reduce((result, item) => Object.assign(result, item), {});
    const { cache } = this;
    this.cache = {
      ...cache,
      ...fetchDataMap,
    };
  };

  getCommonData = async (reqKeyList) => {
    const reqKeys = this.checkReqKeyList(reqKeyList);
    const uncachedReqKeyList = this.filterUncachedKeyList(reqKeys);
    if (uncachedReqKeyList.length === 0) return this.extractCachedCommonData(reqKeys);
    await this.requestUncachedData(uncachedReqKeyList);
    return this.extractCachedCommonData(reqKeys);
  };
}

const cacheProxy = new CommonDataCacheProxy();

export const getCacheDataByKey = cacheProxy.getCommonData;

使用方法:

dispatch({ type: 'queryCommonData', payload: [commonDataKeys.APPLICATION_LIST] });

...

 * queryCommonData({ payload }, { call, put }) {
  const commonData = yield call(getCacheDataByKey, payload);
  yield put({ type: 'applyReduce', payload: { ...commonData } });
},
   
   
// commonData  { applicationList: [...] }


分页数据也可参考此思想

相关文章

  • 公共数据缓存

    公共数据缓存调用 工具方法: 新建一个类,全局一个实例,暴露方法:getCacheDataByKey 1 先判断传...

  • 二级缓存

    数据特点 1、公共的数据2、不经常修改的数据3、私密性不是很高的数据 结构 二级缓存的生命周期 hibernate...

  • 08 | 服务端缓存的分类和介绍

    服务端缓存的种类 数据库缓存; 平台级缓存; 应用级缓存; 数据库缓存 数据库缓存是一种比较特殊的缓存,是数据库自...

  • Redis学习笔记-16 个常见使用场景

    1、缓存 String类型 例如:热点数据缓存,对象缓存、全页缓存、可以提升热点数据的访问数据。 2、数据共享分布...

  • SDWebImage缓存数据的获取/删除

    缓存数据的获取 缓存数据的删除

  • 分布式锁的应用实例

    解决缓存击穿问题 当我们将数据放在缓存中,每次查询先访问缓存,如果缓存中有数据,就直接返回数据,如果没有,就去数据...

  • php缓存技术

    php缓存技术 普遍缓存技术 数据缓存:这里所说的数据缓存是指数据库查询缓存,每次访问页面的时候,都会先检测相应的...

  • php内存缓存实现程序代码

    php内存缓存实现程序代码 1、普遍缓存技术:数据缓存:这里所说的数据缓存是指数据库查询PHP缓存机制,每次访问页...

  • 面试官:缓存与数据库一致性如何解决?先操作数据库,还是缓存?

    本篇文章主要内容 数据缓存 为何要使用缓存 哪类数据适合缓存 缓存的利与弊 如何保证缓存和数据库一致性 不更新缓存...

  • OKhttp的自定义缓存的实现

    1、网络请求框架的缓存基本实现:有缓存用缓存的数据,没缓存发起http请求取数据,得到最新的数据后存到缓存里。 2...

网友评论

      本文标题:公共数据缓存

      本文链接:https://www.haomeiwen.com/subject/zvyfsktx.html