How to deal with expired keys?
The key cache with expire expires, but the server’s memory is still occupied. This is because redis is based on two deletion policies:
- (Active) Delete periodically
- Check expired keys periodically and randomly. If expired keys are deleted. (Check times per second in Redis.conf hz configuration)
- (Passive) Lazy delete
- When a client requests a key that has expired, Redis checks to see if the key is expired, deletes it if it is, and returns nil. This strategy is CPU-friendly and does not incur much loss, but the memory footprint is high.
So, even though the key is out of date, as long as it is not cleaned up by Redis, the memory will still be occupied.
What if the Redis cache is slow?
If the memory is full, you can use a hard disk to save the memory, but there is no point because hard disk is not as fast as memory, which will affect redis performance. So, when MEMORY is full, Redis provides a cache elimination mechanism: MEMORY MANAGEMENT
Maxmemory: When memory usage has reached, the cache is cleared
* Allkeys-lRU: Remove least used old cache, and save new cache (recommended) * allkeys-random: * volatile- lRU: In those caches that have expire time set, the old cache that is least used is cleared, and the new cache is saved * volatile-random: In those caches with expire time set, the cache is randomly deleted * volatile- TTL: in those caches with expire time set, the cache that is about to expire is deletedCopy the code