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

本文共 1827 字,大约阅读时间需要 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/

你可能感兴趣的文章
MySQL Cluster 7.0.36 发布
查看>>
Multimodal Unsupervised Image-to-Image Translation多通道无监督图像翻译
查看>>
MySQL Cluster与MGR集群实战
查看>>
multipart/form-data与application/octet-stream的区别、application/x-www-form-urlencoded
查看>>
mysql cmake 报错,MySQL云服务器应用及cmake报错解决办法
查看>>
Multiple websites on single instance of IIS
查看>>
mysql CONCAT()函数拼接有NULL
查看>>
multiprocessing.Manager 嵌套共享对象不适用于队列
查看>>
multiprocessing.pool.map 和带有两个参数的函数
查看>>
MYSQL CONCAT函数
查看>>
multiprocessing.Pool:map_async 和 imap 有什么区别?
查看>>
MySQL Connector/Net 句柄泄露
查看>>
multiprocessor(中)
查看>>
mysql CPU使用率过高的一次处理经历
查看>>
Multisim中555定时器使用技巧
查看>>
MySQL CRUD 数据表基础操作实战
查看>>
multisim变压器反馈式_穿过隔离栅供电:认识隔离式直流/ 直流偏置电源
查看>>
mysql csv import meets charset
查看>>
multivariate_normal TypeError: ufunc ‘add‘ output (typecode ‘O‘) could not be coerced to provided……
查看>>
MySQL DBA 数据库优化策略
查看>>