Redis design and principle summary-the realization and principle of stand-alone database

The internal structure of the reids database

Insert picture description here
Insert picture description here


Switch to the database

  1. The database recorded by the redis client-the
Insert picture description here


database key space can be switched through select.

Insert picture description here


Insert picture description here


From the above, the operation of the key space is actually the operation of adding, deleting, modifying, checking and reading the dictionary

  1. Add key: add a dictionary object
  2. Delete key: delete the key-value pair object
  3. Update key: update the key-value pair object
  4. There are many other commands that use the key space to implement
    maintenance when reading and writing the key space.
    Remove the expiration time
  5. Determine whether the key or expiration time is set
  6. Perform deletion
    calculation on the expiration time that meets the conditions and return the judgment of the remaining survival time
    expiration time
  7. There are two ways to achieve
  8. Judge directly through the dictionary is_expired (time)
  9. Check whether the expiration time is greater than 0 through TTL or PTTL
  10. Using the first method is better than using the second method. It is more efficient to call the dictionary.
    Expiration time deletion strategy:
    Timing deletion: create a timer, and execute the deletion when the expiration time is about to expire. (Memory-friendly, CPU-friendly, not recommended, occupied Too much CPU affects the throughput of the service)
    Lazy deletion: When operating the key space, first judge whether it is expired (the most CPU-friendly, not memory-friendly, and will not delete the memory after expiration).
    Periodic deletion: every time, the program Perform the deletion operation (Is it: the duration and frequency of the deletion, so the operation must be carried out according to the actual situation of the server)

Expired caching strategy actually used by reids: regular + laziness

Insert picture description here

The implementation of the regular deletion strategy

Insert picture description here


AOF, RDB and the processing of expired keys by the replication function

  1. Generate RDB file, expired will not be stored
  2. RDB file loading, if it is running in the master server mode, it will not be loaded if it expires, but will be loaded from the server
  3. AOF, a key has not been deleted yet, AOF has no effect
  4. After AOF is deleted, add a DEL, then return a null value when get