目录

Redis学习(三)-redis过期机制

此篇主要介绍redis的一些机制

expire删除机制

大家有没有想过redis是怎么实现key的过期删除的,作为有经验的开发人员,也许大家很容易想到以下三个方案:

  1. 每设置一个过期时间就启动一个定时器,时间到的时候删除即可,但是当有大量的key需要过期的时候就显得效率低下。
  2. 懒汉式检查,当我们取值的时候再进行判断,此种方案节约了不少检查的开支,但是如果长期没有进行取值那就行造成存储资源的浪费,而且同一时间进行大量的取值要进行的判断次数很多,cpu的压力陡增。
  3. 定期检查并删除,这样可以解决懒汉式的缺点,但是检查的周期和每次执行的时间要合适,不然会给cpu过多的压力
    这里我们看下redis官网上的介绍

Redis keys are expired in two ways: a passive way, and an active way. A key is passively expired simply when some client tries to access it, and the key is found to be timed out.
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:

  1. Test 20 random keys from the set of keys with an associated expire.
  2. Delete all the keys found expired.
  3. If more than 25% of keys were expired, start again from step 1.

大概意思是说有两个方案可以选择。消极的方法就是客户端请求访问数据的时候再检查是否超时,当然这是不够的,因为有些keys可能再也不会访问到。redis从设置过期的keys中随机的选择一些进行检查。所有过期的key都要从空间中删除。
具体内容,每秒做10次以下步骤:

  1. 随机选择20个key
  2. 删除过期的key
  3. 如果超过25%的key是过期的,继续循环,执行第一步