侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

Redis  /  管理员 发布于 5年前   420

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

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

  • 定时删除:在设置键的过期时间的同时,创建一个定时器( 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,判断是否过期

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


  • 上一条:
    Redis中键值过期操作示例详解
    下一条:
    redis中队列消息实现应用解耦的方法
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在Redis中能实现的功能、常见应用介绍(0个评论)
    • 2024年Redis面试题之一(0个评论)
    • 在redis缓存常见出错及解决方案(0个评论)
    • 在redis中三种特殊数据类型:地理位置、基数(cardinality)估计、位图(Bitmap)使用场景介绍浅析(2个评论)
    • Redis 删除 key用 del 和 unlink 有啥区别?(1个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2017-12
    • 2020-03
    • 2020-05
    • 2021-04
    • 2022-03
    • 2022-05
    • 2022-08
    • 2023-02
    • 2023-04
    • 2023-07
    • 2024-01
    • 2024-02
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客