微信小程序实现缓存过期时间

微信小程序实现缓存过期时间


前言

先来看看官方文档


 wx.setStorageSync(string key, any data)
将数据存储在本地缓存中指定的 key 中。会覆盖掉原来该 key 对应的内容。除非用户主动删除或因存储空间原因被系统清理,否则数据都一直可用。单个 key 允许存储的最大数据长度为 1MB,所有数据存储上限为 10MB。	
注意:需要存储的内容。只支持原生类型、Date、及能够通过JSON.stringify序列化的对象。
	

很遗憾没有过期时间设置, 如果有数据更新, 则需要重新清除本地缓存


我们可以自己写缓存过期逻辑。 思路:在保存对象时, 同时保存一个对象,用于判断过期时间

一、设置缓存

 this.SetCache = function (key, data, milliseconds) {
      if (milliseconds && milliseconds > 0) {
        var curTime = new Date();
        let cacheDateList = []; //时间缓存对象数组,便于后面Get时批量处理过期缓存
        cacheDateList = wx.getStorageSync('cacheDataList');
        if (!cacheDateList || cacheDateList.length == 0) {
          cacheDateList = [];
        }
        let existkey = false;
        cacheDateList.forEach(a => {
          //如果存在则重新更新过期时间
          if (a.key == key) {
            a.invalidtime = curTime.getTime() + milliseconds;
            existkey = true;
          }
        })
        //如果不存在, 则新添加
        if (!existkey) {
          cacheDateList.push({ key: key, invalidtime: curTime.getTime() + milliseconds, interval: milliseconds })
        }
        //设置缓存对象数组
        wx.setStorageSync('cacheDataList', cacheDateList);
      }
      wx.setStorageSync(key, data);
    };

二、得到缓存

 	//获取缓存数据 isSliding 是否滑动缓存请求
    this.GetCache = function (key, isSliding) {
      let cacheDateList = [];
      let curTime = new Date();
      let clist = [];
      cacheDateList = wx.getStorageSync('cacheDataList');
      if (cacheDateList && cacheDateList.length > 0) {
        cacheDateList.forEach(a => {
          //剔除已过期的缓存
          if (a.invalidtime < curTime.getTime()) {          
            wx.removeStorageSync(a.key);
          }
          else {
            if (a.key == key) {
              if (isSliding) {
                a.invalidtime = curTime.getTime() + a.interval;
              }
            }
            clist.push(a);
          }
        });
        wx.setStorageSync('cacheDataList', clist);
      }

      return wx.getStorageSync(key);
    }

总结

通过自定义一个缓存对象,来达到过期时间的设置, 如何清除 wx.setStorageSync(‘cacheDataList’, clist); 对象,或则服务器更新新重置, 可以再从服务器取一个系统版本号写入本地, 当版本号与本地对比不一致时,则直接可清除所有缓存。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值