当前位置:网站首页>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 .
边栏推荐
- HMS core helps baby bus show high-quality children's digital content to global developers
- 165 webmaster online toolbox website source code / hare online tool system v2.2.7 Chinese version
- C language - Introduction - Foundation - syntax - [identifier, keyword, semicolon, space, comment, input and output] (III)
- Investment analysis and prospect prediction report of global and Chinese high purity tin oxide Market Ⓞ 2022 ~ 2027
- Sequence model
- Global and Chinese markets of water heaters in Saudi Arabia 2022-2028: Research Report on technology, participants, trends, market size and share
- Simulate EF dbcontext with MOQ - mocking EF dbcontext with MOQ
- Explanation of for loop in golang
- The map set type is stored in the form of key value pairs, and the iterative traversal is faster than the list set
- Awk from entry to earth (15) awk executes external commands
猜你喜欢
Jianzhi offer 09 realizes queue with two stacks
C语言-入门-基础-语法-[标识符,关键字,分号,空格,注释,输入和输出](三)
C语言-入门-基础-语法-[运算符,类型转换](六)
地平线 旭日X3 PI (一)首次开机细节
2022-2028 global protein confectionery industry research and trend analysis report
2022-2028 global special starch industry research and trend analysis report
How to ensure the uniqueness of ID in distributed environment
C language - Introduction - Foundation - syntax - [operators, type conversion] (6)
Horizon sunrise X3 PI (I) first boot details
AMLOGIC gsensor debugging
随机推荐
The map set type is stored in the form of key value pairs, and the iterative traversal is faster than the list set
Some points needing attention in PMP learning
Awk from entry to penetration (6) regular matching
[error record] no matching function for call to 'cacheflush' cacheflush();)
C语言-入门-基础-语法-数据类型(四)
C语言-入门-基础-语法-[变量,常亮,作用域](五)
Global and Chinese markets of thrombography hemostasis analyzer (TEG) 2022-2028: Research Report on technology, participants, trends, market size and share
How should PMP learning ideas be realized?
Explanation of for loop in golang
C语言-入门-基础-语法-[运算符,类型转换](六)
[on February 11, 2022, the latest and most fully available script library collection of the whole network, a total of 23]
LinkedList in the list set is stored in order
Use Alibaba cloud NPM image acceleration
After unplugging the network cable, does the original TCP connection still exist?
2022-2028 global probiotics industry research and trend analysis report
Awk from getting started to digging in (11) detailed explanation of awk getline function
Research Report on the current market situation and development prospects of calcium sulfate whiskers in China (2022 Edition)
Research and investment strategy report of China's electronic hydrogen peroxide industry (2022 Edition)
165 webmaster online toolbox website source code / hare online tool system v2.2.7 Chinese version
Explanation of closures in golang