参考文章链接 https://redis.io/commands/expire。
1.redis有两种key的失效机制
1.被动失效 。
A key is passively expired simply when some client tries to access it, and the key is found to be timed out.
当客户端去获取key的时候,去判断key是否失效。
2.主动失效
Of course this is not enough as there are expired keys that will never be accessed again. These keys should be expired anyway, so periodically Redis tests a few keys at random among keys with an expire set. All the keys that are already expired are deleted from the keyspace.
Specifically this is what Redis does 10 times per second:
- Test 20 random keys from the set of keys with an associated expire.
- Delete all the keys found expired.
- If more than 25% of keys were expired, start again from step 1.
redis有一个定时任务每秒执行10次。
第一步,从有失效机制的key中随机取出20个key。
第二步,删除已经过期的key。
第三部,判断下是否超过1/4的key已经失效了,如果没有执行步骤第一步。
这样就可以保证在任何时间,过期的key占用的内存空间的最大值 是 每秒写操作 key/4.