博客
关于我
【redis键过期删除策略】很高兴再次认识你
阅读量:296 次
发布时间:2019-03-03

本文共 1829 字,大约阅读时间需要 6 分钟。

【redis键过期删除策略】很高兴再次认识你

三种删除策略

在不考虑redis实现方式的情况下,我们自己手动设计一个删除有时间限制的key有几种策略?

  • 定时删除:在创建完一个key时,同时创建一个定时任务,监听key是否过期。

  • 定期删除:设置好周期之后,间断性的扫描key,然后删除过期的key。(这里的扫描方式拓展开来也可以划分为全部扫还是随机部分扫,随机的发方式又可以怎样设计)

  • 惰性删除:联想ThreadLocal的实现方式。前两两个都是主动去做删除,那如果我喜欢被动,在条件允许的情况下,可以要用时做一个判断,if(过期)then(删除)。

redis采取的方式

再来考虑redis的实现方式,它采用定期删除惰性删除的方式。定时删除不可取,特别是在缓存的内容过期时间还都不一样的情况下。因为这会耗费更多得CPU时间,且有可能还是做无用功的耗费。(删除的时间还未到缺占着CPU)

定期删除

关于redis的定期删除,它也不对去遍历所有的key,而是分了多次去遍历redis的各个数据库中expires字典(键为我们存的key,内容为过期时间点)。遍历的进度和遍历执行的时间限制会通过如下几个全局变量保存。

  /* This function has some global state in order to continue the work     * incrementally across calls. */    static unsigned int current_db = 0; /* Last DB tested. */    static int timelimit_exit = 0;      /* Time limit hit in previous call? */    static long long last_fast_cycle = 0; /* When last fast cycle ran. */

惰性删除

在实际访问到数据的时候,通过db.c#expireIfNeeded方法去判断是否过期,过期时先做删除,再执行相关命令的流程,如get操作时返回nil

int expireIfNeeded(redisDb *db, robj *key) {       if (!keyIsExpired(db,key)) return 0;    /* If we are running in the context of a slave, instead of     * evicting the expired key from the database, we return ASAP:     * the slave key expiration is controlled by the master that will     * send us synthesized DEL operations for expired keys.     *     * Still we try to return the right information to the caller,     * that is, 0 if we think the key should be still valid, 1 if     * we think the key is expired at this time. */    if (server.masterhost != NULL) return 1;    /* Delete the key */    server.stat_expiredkeys++;    propagateExpire(db,key,server.lazyfree_lazy_expire);    notifyKeyspaceEvent(NOTIFY_EXPIRED,        "expired",key,db->id);        // 这里感觉比较有趣,根据配置的策略还会选择做同步删还是异步删除    return server.lazyfree_lazy_expire ? dbAsyncDelete(db,key) :                                         dbSyncDelete(db,key);}

转载地址:http://rlxm.baihongyu.com/

你可能感兴趣的文章
scanf gets fgets的差别
查看>>
二叉树知识点集合
查看>>
归并排序
查看>>
Xshell小键盘不能使用,反斜杠不能输入
查看>>
圆圈中最后剩下的数字(约瑟夫环)
查看>>
将ip地址用整形保存
查看>>
PS--给图片加水印技巧
查看>>
图片偏移
查看>>
Azure上的时序见解,time series insights
查看>>
Azure安全系列(3)-Application Gateway 中的 Web应用防火墙
查看>>
Azure IoT Edge入门(2)部署一台Edge Device
查看>>
在Windows 10中启动WSL2 并安装Linux( Ubuntu 为例)并运行docker
查看>>
appium(1)环境安装
查看>>
VUE初学者------------初始化一个vue项目
查看>>
「小程序JAVA实战」小程序数据缓存API(54)
查看>>
『互联网架构』软件架构-mybatis体系结构(14)
查看>>
软件架构-zookeeper快速入门
查看>>
软件架构-zookeeper场景和实现
查看>>
身边到处是牛人,开发就这么坑!
查看>>
自己的利益靠自己争取,开发就是这么坑!
查看>>