Using lazy delete and timed delete to realize the local storage cache that can expire

Introduction to localStorage

Use localStorage to store data for key value pairs in the browser. sessionStorage is often mentioned together with localStorage, which can store the data of key value pairs in the browser. But the difference between them is: the data stored in localStorage can be kept for a long time; when the page session ends (that is, when the page is closed), the data stored in sessionStorage will be cleared.

In addition, it should be noted that the key value pairs in localStorage are always stored in the form of strings, and can only access the data under the current domain name, not across domain names.

Welcome to WeChat official account: Wan Mao society, dry cargo Java technology every Monday.

localStorage method

You can add a key value pair of data through the setItem method, for example:

localStorage.setItem('name', 'OneMore');

If the key already exists, the value corresponding to the key will be overwritten. You can also use the getItem method to read the value data of the corresponding key, for example:

var name = localStorage.getItem('name');

You can use the removeItem method to remove the corresponding key, for example:

localStorage.removeItem('name');

You can also use the clear method to remove all key value pairs under the current domain name, such as:

localStorage.clear();

Welcome to WeChat official account: Wan Mao society, dry cargo Java technology every Monday.

Expiring localStorage cache

As mentioned above, localStorage can only be used to save the data of the entire website for a long time. The saved data has no expiration time until it is deleted manually. So the key point of realizing the local storage cache that can expire is: how to clean up the expired cache?

Lazy delete

Lazy deletion means that when a key value expires, it will not be deleted immediately, but will not be checked until the next time it is used, and then it can be deleted. Let's implement it briefly:

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 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 value data of corresponding key
     * @param key key
     * @returns {null|*} Value of corresponding key
     */
    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 || {}));

The above code has implemented the local storage cache that can expire through lazy deletion, but it also has obvious disadvantages: if a key has not been used, it will always be stored in the local storage even if it has expired. To make up for this, we introduce another strategy to clean up the expired cache.

Welcome to WeChat official account: Wan Mao society, dry cargo Java technology every Monday.

Scheduled deletion

Scheduled deletion means that the deletion operation is performed once every other period of time, and the long-term CPU occupation of the deletion operation is reduced by limiting the number and frequency of the deletion operation. On the other hand, scheduled deletion also effectively reduces the waste of local storage space caused by lazy deletion.

Regularly delete every second as follows:

  1. Randomly test 20 key s with expiration time set.
  2. Delete all discovered expired key s.
  3. If more than 5 key s are deleted, repeat step 1 until 500 times.

The specific implementation is as follows:

var lsc = (function (self) {
    var prefix = 'one_more_lsc_'
    var list = [];
    //Initialize list
    self.init = function () {
        var keys = Object.keys(localStorage);
        var reg = new RegExp('^' + prefix);
        var temp = [];
        //Traverse all key s in all localStorage
        for (var i = 0; i < keys.length; i++) {
        	//Find out the key that can expire the cache
            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;
            //Randomly test 20 key s with expiration time set
            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]);
                //Delete the inert deleted key from the list
                if (!val) {
                    list.splice(index, 1);
                    expireCount++;
                    continue;
                }
                val = JSON.parse(val);
                //Delete all discovered expired key s
                if (val.expires < new Date().getTime()) {
                    list.splice(index, 1);
                    localStorage.removeItem(key);
                    expireCount++;
                }
            }
            //If no more than 5 key s are deleted, the cycle will pop out
            if (expireCount <= 5 || list.length == 0) {
                break;
            }
            checkCount++;
        }
    }
    //Perform a scheduled delete every second
    window.setInterval(self.check, 1000);
    return self;
}(lsc || {}));

Complete source code and use example

The complete source code and use examples have been uploaded to My GitHub(https://github.com/heihaozi/LocalStorageCache )Thank you, Star and Fork.

summary

One strategy may have its own shortcomings. In order to avoid the corresponding shortcomings, we can reasonably use a variety of strategies to develop the strengths and avoid the weaknesses to get a nearly perfect solution.

WeChat official account: Wan Mao Society

Wechat scan QR code

Get more Java technology dry goods

Tags: Javascript Java JSON github Session

Posted on Sun, 31 May 2020 21:56:24 -0400 by systemtek