当前位置: 移动技术网 > IT编程>数据库>Redis > Redis中键的过期删除策略深入讲解

Redis中键的过期删除策略深入讲解

2018年09月23日  | 移动技术网IT编程  | 我要评论
如果一个键过期了,那么它什么时候会被删除呢? 这个问题有三种可能的答案,它们分别代表了三种不同的删除策略: 定时删除:在设置键的过期时间的同时,

如果一个键过期了,那么它什么时候会被删除呢?

这个问题有三种可能的答案,它们分别代表了三种不同的删除策略:

  • 定时删除:在设置键的过期时间的同时,创建一个定时器( timer ). 让定时器在键的过期时间来临时,立即执行对键的删除操作。
  • 惰性删除:放任键过期不管,但是每次从键空间中获取键时,都检查取得的键是否过期,如果过期的话,就删除该键;如果没有过期,就返回该键。
  • 定期删除: 每隔一段时间,程序就对数据库进行一次检查,删除里面的过期键。至于要删除多少过期键,以及要检查多少个数据库, 则由算法决定。

在这三种策略中,第一种和第三种为主动删除策略, 而第二种则为被动删除策略。

前言

使用redis时我们可以使用expire或expireat命令给key设置过期删除时间,结构体redisdb中的expires字典保存了所有key的过期时间,这个字典(dict)的key是一个指针,指向redis中的某个key对象,过期字典的value是一个保存过期时间的整数。

/* redis database representation. there are multiple databases identified
 * by integers from 0 (the default database) up to the max configured
 * database. the database number is the 'id' field in the structure. */
typedef struct redisdb {
 dict *dict;     /* the keyspace for this db */
 dict *expires;    /* 过期字典*/
 dict *blocking_keys;  /* keys with clients waiting for data (blpop) */
 dict *ready_keys;   /* blocked keys that received a push */
 dict *watched_keys;   /* watched keys for multi/exec cas */
 struct evictionpoolentry *eviction_pool; /* eviction pool of keys */
 int id;      /* database id */
 long long avg_ttl;   /* average ttl, just for stats */
} redisdb;

设置过期时间

不论是expire,expireat,还是pexpire,pexpireat,底层的具体实现是一样的。在redis的key空间中找到要设置过期时间的这个key,然后将这个entry(key的指针,过期时间)加入到过期字典中。

void setexpire(redisdb *db, robj *key, long long when) {
 dictentry *kde, *de;

 /* reuse the sds from the main dict in the expire dict */
 kde = dictfind(db->dict,key->ptr);
 redisassertwithinfo(null,key,kde != null);
 de = dictreplaceraw(db->expires,dictgetkey(kde));
 dictsetsignedintegerval(de,when);
}

过期删除策略

如果一个key过期了,何时会被删除呢?在redis中有两种过期删除策略:(1)惰性过期删除;(2)定期删除。接下来具体看看。

惰性过期删除

redis在执行任何读写命令时都会先找到这个key,惰性删除就作为一个切入点放在查找key之前,如果key过期了就删除这个key。


robj *lookupkeyread(redisdb *db, robj *key) {
 robj *val;

 expireifneeded(db,key); // 切入点
 val = lookupkey(db,key);
 if (val == null)
  server.stat_keyspace_misses++;
 else
  server.stat_keyspace_hits++;
 return val;
}

定期删除

key的定期删除会在redis的周期性执行任务(servercron,默认每100ms执行一次)中进行,而且是发生redis的master节点,因为slave节点会通过主节点的del命令同步过来达到删除key的目的。


依次遍历每个db(默认配置数是16),针对每个db,每次循环随机选择20个(active_expire_cycle_lookups_per_loop)key判断是否过期,如果一轮所选的key少于25%过期,则终止迭次,此外在迭代过程中如果超过了一定的时间限制则终止过期删除这一过程。

for (j = 0; j < dbs_per_call; j++) {
 int expired;
 redisdb *db = server.db+(current_db % server.dbnum);

 /* increment the db now so we are sure if we run out of time
  * in the current db we'll restart from the next. this allows to
  * distribute the time evenly across dbs. */
 current_db++;

 /* continue to expire if at the end of the cycle more than 25%
  * of the keys were expired. */
 do {
  unsigned long num, slots;
  long long now, ttl_sum;
  int ttl_samples;

  /* 如果该db没有设置过期key,则继续看下个db*/
  if ((num = dictsize(db->expires)) == 0) {
   db->avg_ttl = 0;
   break;
  }
  slots = dictslots(db->expires);
  now = mstime();

  /* when there are less than 1% filled slots getting random
   * keys is expensive, so stop here waiting for better times...
   * the dictionary will be resized asap. */
  if (num && slots > dict_ht_initial_size &&
   (num*100/slots < 1)) break;

  /* the main collection cycle. sample random keys among keys
   * with an expire set, checking for expired ones. */
  expired = 0;
  ttl_sum = 0;
  ttl_samples = 0;

  if (num > active_expire_cycle_lookups_per_loop)
   num = active_expire_cycle_lookups_per_loop;// 20

  while (num--) {
   dictentry *de;
   long long ttl;

   if ((de = dictgetrandomkey(db->expires)) == null) break;
   ttl = dictgetsignedintegerval(de)-now;
   if (activeexpirecycletryexpire(db,de,now)) expired++;
   if (ttl > 0) {
    /* we want the average ttl of keys yet not expired. */
    ttl_sum += ttl;
    ttl_samples++;
   }
  }

  /* update the average ttl stats for this database. */
  if (ttl_samples) {
   long long avg_ttl = ttl_sum/ttl_samples;

   /* do a simple running average with a few samples.
    * we just use the current estimate with a weight of 2%
    * and the previous estimate with a weight of 98%. */
   if (db->avg_ttl == 0) db->avg_ttl = avg_ttl;
   db->avg_ttl = (db->avg_ttl/50)*49 + (avg_ttl/50);
  }

  /* we can't block forever here even if there are many keys to
   * expire. so after a given amount of milliseconds return to the
   * caller waiting for the other active expire cycle. */
  iteration++;
  if ((iteration & 0xf) == 0) { /* 每迭代16次检查一次 */
   long long elapsed = ustime()-start;

   latencyaddsampleifneeded("expire-cycle",elapsed/1000);
   if (elapsed > timelimit) timelimit_exit = 1;
  }
 // 超过时间限制则退出
  if (timelimit_exit) return;
  /* 在当前db中,如果少于25%的key过期,则停止继续删除过期key */
 } while (expired > active_expire_cycle_lookups_per_loop/4);
}

总结

惰性删除:读写之前判断key是否过期

定期删除:定期抽样key,判断是否过期

好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网