Redis expired key removal strategy analysis

  • How Redis eliminates expired keys: set name daniel 3600

    • Lazy deletion:

      • Concept: When some clients try to access it, the key will be discovered and actively expired

      • Let the key expire regardless, but every time you get a key from the key space, check whether the obtained key has expired, if it expires, delete the key

      • Features: CPU friendly , but if a key is no longer used, it will always exist in the memory, causing waste

         

    • Timed deletion:

      • Concept: When setting the expiration time of the key, create a timer (timer), let the timer execute the delete operation of the key immediately when the expiration time of the key comes.

         

    • Delete regularly:

      • After a while, the program will check the database and delete the expired keys. As for how many expired keys should be deleted,

        And the number of databases to be checked is determined by the algorithm. That is to set up a timed task, such as deleting expired keys every 10 minutes; small intervals will occupy CPU, and large intervals will waste memory

      • For example, Redis processes every second:

      1. Test 20 random keys for related expiration detection.

      2. Delete all expired keys.

      3. If more than 25% of the keys expire, repeat step 1.

     

The Redis server actually uses two strategies of lazy deletion and periodic deletion: by using these two deletion strategies together, the server can achieve a good balance between rational use of CPU time and avoiding wasting memory space.

 

How is the lazy deletion strategy implemented? Through the expireIfNeeded function, we judge whether the key expires when we manipulate the key

How is the regular deletion strategy implemented? Through the activeExpireCycle function, when the serverCron function is executed, the activeExpireCycle function will be called. The expires dictionary of the server is traversed multiple times within the specified time to randomly check the expiration time of a part of the key, and delete the expired key

Guess you like

Origin blog.csdn.net/qq_41023026/article/details/89739343