Redis cache expiration strategy

There are usually three Redis cache expiration strategies:

1. Timed expiration

Each key that sets the expiration time needs to create a timer, and it will be cleared immediately when the expiration time is reached.

Advantages: This strategy can immediately clear expired data, which is very memory friendly;

Disadvantages: If there are many expired keys, deleting these keys will take up a lot of CPU resources to process expired data, thereby affecting performance.

Second, inert expiration

Only when a key is accessed, will it be judged whether the key has expired, and it will be cleared if it expires.

Advantages: This strategy can maximize the saving of CPU resources: the delete operation only occurs when the key is taken out, and only the current key is deleted, so the CPU time is relatively small, and the deletion at this time has already been done. Unacceptable point (if not deleted at this time, we will get the key that has expired)

Disadvantages: Very unfriendly to memory. In extreme cases, a large number of expired keys may not be accessed again, so that they will not be cleared, occupy a lot of memory, and even cause memory leaks.

Three, regular expiration

At regular intervals, a certain number of keys will be scanned and the expired keys will be cleared.

This strategy is a compromise between the first two. By adjusting the time interval of the timing scan and the time-consuming limit of each scan, the CPU and memory resources can be optimally balanced under different circumstances.

Guess you like

Origin blog.csdn.net/baidu_24752135/article/details/114269488