localstorage实现带过时时间的缓存功能

 

前言

通常可使用cookie,localstorage,sessionStorage来实现浏览器端的数据缓存,减小对服务器的请求。git

1.cookie数据存放在本地硬盘中,只要在过时时间以前,都是有效的,即便重启浏览器。可是会在每次HTTP请求中添加到请求头中,若是数据过多,会形成性能问题。github

2.sessionStorage保存在浏览器内存中,当关闭页面或者浏览器以后,信息丢失。浏览器

3.localstorage也是保存在本地硬盘中,除非主动清除,信息是不会消失的。可是实际使用时咱们须要对缓存设置过时时间,本文即是讲解如何为localstorage添加过时时间功能。缓存

这三者仅支持同源(host+port)的数据,不一样源的数据不能互相访问到。服务器

 

localstorage

localstorage支持如下方法cookie

保存数据:localStorage.setItem(key,value); 读取数据:localStorage.getItem(key); 删除单个数据:localStorage.removeItem(key); 删除全部数据:localStorage.clear(); 获得某个索引的key:localStorage.key(index); 

 

须要注意的是,仅支持String类型数据的读取,若是存放的是数值类型,读出来的是字符串类型的,对于存储对象类型的,须要在保存以前JSON化为String类型。session

对于缓存,咱们通常有如下方法性能

set(key,value,expiredTime); get(key); remove(key); expired(key,expiredTime); clear();

 

实现

设置缓存

对于过时时间的实现,除了用于存放原始值的缓存(key),这里添加了两个缓存(key+EXPIRED:TIME)和(key+EXPIRED:START:TIME),一个用于存放过时时间,一个用于存放缓存设置时的时间。spa

当读取的时候比较 (过时时间+设置缓存的时间)和当前的时间作对比。若是(过时时间+设置缓存时的时间)大于当前的时间,则说明缓存没过时。localstorage

注意这里使用JSON.stringify对存入的对象JSON化。读取的时候也要转回原始对象。

"key":{ //辅助
        "expiredTime": "EXPIRED:TIME", "expiredStartTime": "EXPIRED:START:TIME", //全局使用
        //用户信息
        "loginUserInfo": "USER:INFO", //搜索字段
        "searchString": "SEARCH:STRING", }, /** * 设置缓存 * @param key * @param value * @param expiredTimeMS 过时时间,单位ms */
    "set":function (key,value,expiredTimeMS) { if((expiredTimeMS == 0 )  || (expiredTimeMS == null)){ localStorage.setItem(key,value); } else { localStorage.setItem(key,JSON.stringify(value)); localStorage.setItem(key+cache.key.expiredTime,expiredTimeMS); localStorage.setItem(key+cache.key.expiredStartTime,new Date().getTime()); } },

 

 

读取缓存

因为读取出来的是时间信息是字符串,须要将其转化为数字再进行比较。

/** * 获取键 * @param key * @returns {*} key存在,返回对象;不存在,返回null */
    "get":function (key) { var expiredTimeMS = localStorage.getItem(key+cache.key.expiredTime); var expiredStartTime = localStorage.getItem(key+cache.key.expiredStartTime); var curTime = new Date().getTime(); var sum = Number(expiredStartTime)  + Number(expiredTimeMS); if((sum) > curTime){ console.log("cache-缓存["+key+"]存在!"); return JSON.parse(localStorage.getItem(key)); } else { console.log("cache-缓存["+key+"]不存在!"); return null; } },

 

移除缓存

移除缓存时须要把三个键同时移除。

/** * 移除键 * @param key */
    "remove":function (key) { localStorage.removeItem(key); localStorage.removeItem(key+cache.key.expiredTime); localStorage.removeItem(key+cache.key.expiredStartTime); },

 

其余代码

/** * 对键从新更新过时时间 * @param key * @param expiredTimeMS 过时时间ms */
    "expired":function (key,expiredTimeMS) { if(cache.get(key)!=null){ localStorage.setItem(key+cache.key.expiredTime,expiredTimeMS); } }, /** * 清除全部缓存 */
    "clear":function () { localStorage.clear(); }

 

 

本文完整代码 缓存

====

相关文章
相关标签/搜索