当前位置:网站首页>Implementing expired localstorage cache with lazy deletion and scheduled deletion
Implementing expired localstorage cache with lazy deletion and scheduled deletion
2022-07-04 09:25:00 【Wanmao Society】
localStorage brief introduction
Use localStorage The data of key value pairs can be stored in the browser . Often and localStorage Also mentioned is sessionStorage, Both of them can store the data of key value pairs in the browser . But the difference between them is : Stored in localStorage The data can be kept for a long time ; And when the page session ends ( That is, when the page is closed ) when , Stored in sessionStorage The data will be cleared .
Another thing to note ,localStorage Key value pairs in are always stored as strings , And can only access the data under the current domain name , Can't cross domain access .
localStorage Method
Can pass setItem
Method adds a key value pair to the data , such as :
localStorage.setItem('name', 'OneMore');
Copy code
If the key already exists , Then the value corresponding to the key will be overwritten . You can also use getItem
Method to read the value data of the corresponding key , such as :
var name = localStorage.getItem('name');
Copy code
have access to removeItem
Method to remove the corresponding key , such as :
localStorage.removeItem('name');
Copy code
You can also use clear
Method to remove all key value pair data under the current domain name , such as :
localStorage.clear();
Copy code
Expirable localStorage cache
As mentioned above ,localStorage It can only be used to save the data of the whole website for a long time , Saved data has no expiration time , Until you delete it manually . Therefore, we should realize the expiration localStorage The focus of caching is : How to clean up expired cache ?
Lazy deletion
Inert deletion means , After a key value expires , The key value will not be deleted immediately , But wait until the next time it is used , Will be checked to expire , Only then can it be deleted . Let's make it simple :
var lsc = (function (self) {
var prefix = 'one_more_lsc_'
/** * Add a key value pair to the data * @param key key * @param val value * @param expires Expiration time , The unit is in seconds */
self.set = function (key, val, expires) {
key = prefix + key;
val = JSON.stringify({'val': val, 'expires': new Date().getTime() + expires * 1000});
localStorage.setItem(key, val);
};
/** * Read the value data of the corresponding key * @param key key * @returns {null|*} The value of the corresponding bond */
self.get = function (key) {
key = prefix + key;
var val = localStorage.getItem(key);
if (!val) {
return null;
}
val = JSON.parse(val);
if (val.expires < new Date().getTime()) {
localStorage.removeItem(key);
return null;
}
return val.val;
};
return self;
}(lsc || {}));
Copy code
The above code has realized expirable through lazy deletion localStorage cache , But there are also obvious shortcomings : If one key Has not been used , Even if it has expired, it will always be stored in localStorage. In order to make up for such shortcomings , We introduce another strategy to clean up expired caches .
Delete regularly
Scheduled deletion refers to , Delete every other period of time , And by limiting the number and frequency of deletion operations , To reduce the number of delete operations CPU Long term occupation of . On the other hand, scheduled deletion also effectively reduces the impact of lazy deletion on localStorage Waste of space .
Perform scheduled deletion every second , The operation is as follows :
- Random test 20 With expiration time set key.
- Delete all found expired key.
- If you delete key exceed 5 One repeats step 1, Until repeated 500 Time .
The specific implementation is as follows :
var lsc = (function (self) {
var prefix = 'one_more_lsc_'
var list = [];
// initialization list
self.init = function () {
var keys = Object.keys(localStorage);
var reg = new RegExp('^' + prefix);
var temp = [];
// Traverse all of localStorage All in key
for (var i = 0; i < keys.length; i++) {
// Find the cache that can expire key
if (reg.test(keys[i])) {
temp.push(keys[i]);
}
}
list = temp;
};
self.init();
self.check = function () {
if (!list || list.length == 0) {
return;
}
var checkCount = 0;
while (checkCount < 500) {
var expireCount = 0;
// Random test 20 With expiration time set key
for (var i = 0; i < 20; i++) {
if (list.length == 0) {
break;
}
var index = Math.floor(Math.random() * list.length);
var key = list[index];
var val = localStorage.getItem(list[index]);
// from list Delete the inert deleted key
if (!val) {
list.splice(index, 1);
expireCount++;
continue;
}
val = JSON.parse(val);
// Delete all found expired key
if (val.expires < new Date().getTime()) {
list.splice(index, 1);
localStorage.removeItem(key);
expireCount++;
}
}
// If you delete key No more than 5 One jumps out of the loop
if (expireCount <= 5 || list.length == 0) {
break;
}
checkCount++;
}
}
// Perform scheduled deletion every second
window.setInterval(self.check, 1000);
return self;
}(lsc || {}));
Copy code
Complete source code and use examples
The complete source code and usage examples have been uploaded to my GitHub(github.com/heihaozi/Lo…
summary
A strategy may have its own shortcomings , In order to avoid the corresponding shortcomings , We can use a variety of strategies , Develop strengths and avoid weaknesses to get a near perfect solution .
边栏推荐
- C语言-入门-基础-语法-[变量,常亮,作用域](五)
- Development trend and market demand analysis report of high purity tin chloride in the world and China Ⓔ 2022 ~ 2027
- 【LeetCode 42】501. Mode in binary search tree
- ArrayBuffer
- Lauchpad X | 模式
- Target detection -- intensive reading of yolov3 paper
- Use Alibaba cloud NPM image acceleration
- What is uid? What is auth? What is a verifier?
- 2022-2028 global intelligent interactive tablet industry research and trend analysis report
- 2022-2028 research and trend analysis report on the global edible essence industry
猜你喜欢
C语言-入门-基础-语法-[运算符,类型转换](六)
C語言-入門-基礎-語法-[運算符,類型轉換](六)
HMS core helps baby bus show high-quality children's digital content to global developers
How to ensure the uniqueness of ID in distributed environment
How do microservices aggregate API documents? This wave of show~
Live in a dream, only do things you don't say
2022-2028 global protein confectionery industry research and trend analysis report
Implementation principle of redis string and sorted set
2022-2028 global elastic strain sensor industry research and trend analysis report
[C Advanced] file operation (2)
随机推荐
Flutter tips: various fancy nesting of listview and pageview
Global and Chinese market of bipolar generators 2022-2028: Research Report on technology, participants, trends, market size and share
C语言-入门-基础-语法-[标识符,关键字,分号,空格,注释,输入和输出](三)
What is uid? What is auth? What is a verifier?
Solution to null JSON after serialization in golang
[C Advanced] file operation (2)
到底什么才是DaaS数据即服务?别再被其他DaaS概念给误导了
Investment analysis and future production and marketing demand forecast report of China's paper industry Ⓥ 2022 ~ 2028
2022-2028 global intelligent interactive tablet industry research and trend analysis report
C语言-入门-基础-语法-数据类型(四)
Awk from getting started to digging in (11) detailed explanation of awk getline function
Awk from entry to penetration (6) regular matching
Explanation of closures in golang
Function comparison between cs5261 and ag9310 demoboard test board | cost advantage of cs5261 replacing ange ag9310
MySQL foundation 02 - installing MySQL in non docker version
After unplugging the network cable, does the original TCP connection still exist?
If you can quickly generate a dictionary from two lists
The 14th five year plan and investment risk analysis report of China's hydrogen fluoride industry 2022 ~ 2028
Flutter 小技巧之 ListView 和 PageView 的各种花式嵌套
Service call feign of "micro service"