当前位置:网站首页>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 language - Introduction - Foundation - syntax - [main function, header file] (II)
- LeetCode 74. Search 2D matrix
- UML 时序图[通俗易懂]
- 【leetcode】29. Divide two numbers
- CLion-控制台输出中文乱码
- Mac platform forgets the root password of MySQL
- Report on investment analysis and prospect trend prediction of China's MOCVD industry Ⓤ 2022 ~ 2028
- 地平线 旭日X3 PI (一)首次开机细节
- After unplugging the network cable, does the original TCP connection still exist?
- 到底什么才是DaaS数据即服务?别再被其他DaaS概念给误导了
猜你喜欢

Relationship and operation of random events

2022-2028 global edible probiotic raw material industry research and trend analysis report

2022-2028 global industry research and trend analysis report on anterior segment and fundus OTC detectors

到底什么才是DaaS数据即服务?别再被其他DaaS概念给误导了

保姆级JDEC增删改查练习
](/img/3f/4d8f4c77d9fde5dd3f53ef890ecfa8.png)
C語言-入門-基礎-語法-[運算符,類型轉換](六)

Function comparison between cs5261 and ag9310 demoboard test board | cost advantage of cs5261 replacing ange ag9310

How to ensure the uniqueness of ID in distributed environment

2022-2028 global gasket metal plate heat exchanger industry research and trend analysis report

Sword finger offer 30 contains the stack of Min function
随机推荐
How do microservices aggregate API documents? This wave of show~
Awk from getting started to digging in (11) detailed explanation of awk getline function
Global and Chinese market of air fryer 2022-2028: Research Report on technology, participants, trends, market size and share
C语言-入门-基础-语法-[运算符,类型转换](六)
[on February 11, 2022, the latest and most fully available script library collection of the whole network, a total of 23]
Deadlock in channel
【LeetCode 42】501. Mode in binary search tree
Flutter tips: various fancy nesting of listview and pageview
Global and Chinese markets of hemoglobin analyzers in care points 2022-2028: Research Report on technology, participants, trends, market size and share
Explain TCP protocol in detail three handshakes and four waves
Awk from getting started to digging in (9) circular statement
[C Advanced] file operation (2)
You can see the employment prospects of PMP project management
"How to connect the Internet" reading notes - FTTH
Live in a dream, only do things you don't say
Global and Chinese market of bipolar generators 2022-2028: Research Report on technology, participants, trends, market size and share
If you can quickly generate a dictionary from two lists
[untitled] forwarding least square method
LinkedList in the list set is stored in order
Mantis creates users without password options