当前位置:网站首页>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 .
边栏推荐
- Solution to null JSON after serialization in golang
- The 14th five year plan and investment risk analysis report of China's hydrogen fluoride industry 2022 ~ 2028
- Launpad | basic knowledge
- C language - Introduction - Foundation - syntax - data type (4)
- AMLOGIC gsensor debugging
- [untitled] forwarding least square method
- 《网络是怎么样连接的》读书笔记 - FTTH
- Jianzhi offer 09 realizes queue with two stacks
- 2022-2028 global elastic strain sensor industry research and trend analysis report
- UML sequence diagram [easy to understand]
猜你喜欢
How should PMP learning ideas be realized?
C语言-入门-基础-语法-[主函数,头文件](二)
Sword finger offer 30 contains the stack of Min function
Latex download installation record
C语言-入门-基础-语法-[运算符,类型转换](六)
Markdown syntax
C language - Introduction - Foundation - syntax - [operators, type conversion] (6)
C语言-入门-基础-语法-[标识符,关键字,分号,空格,注释,输入和输出](三)
HMS core helps baby bus show high-quality children's digital content to global developers
2022-2028 global seeder industry research and trend analysis report
随机推荐
Awk from entry to earth (7) conditional statements
"How to connect the Internet" reading notes - FTTH
UML sequence diagram [easy to understand]
How to write unit test cases
C语言-入门-基础-语法-[主函数,头文件](二)
Flutter 小技巧之 ListView 和 PageView 的各種花式嵌套
2022-2028 global seeder industry research and trend analysis report
2022-2028 global protein confectionery industry research and trend analysis report
After unplugging the network cable, does the original TCP connection still exist?
After unplugging the network cable, does the original TCP connection still exist?
UML 时序图[通俗易懂]
Global and Chinese market of planar waveguide optical splitter 2022-2028: Research Report on technology, participants, trends, market size and share
Some points needing attention in PMP learning
Explanation of for loop in golang
Talk about single case mode
2022-2028 global probiotics industry research and trend analysis report
China electronic grade sulfur trioxide Market Forecast and investment strategy report (2022 Edition)
Global and Chinese market of sampler 2022-2028: Research Report on technology, participants, trends, market size and share
C language - Introduction - Foundation - syntax - data type (4)
Dynamic analysis and development prospect prediction report of high purity manganese dioxide in the world and China Ⓡ 2022 ~ 2027