博客
关于我
【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/

你可能感兴趣的文章
mysql8的安装与卸载
查看>>
MySQL8,体验不一样的安装方式!
查看>>
MySQL: Host '127.0.0.1' is not allowed to connect to this MySQL server
查看>>
Mysql: 对换(替换)两条记录的同一个字段值
查看>>
mysql:Can‘t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock‘解决方法
查看>>
MYSQL:基础——3N范式的表结构设计
查看>>
MYSQL:基础——触发器
查看>>
Mysql:连接报错“closing inbound before receiving peer‘s close_notify”
查看>>
mysqlbinlog报错unknown variable ‘default-character-set=utf8mb4‘
查看>>
mysqldump 参数--lock-tables浅析
查看>>
mysqldump 导出中文乱码
查看>>
mysqldump 导出数据库中每张表的前n条
查看>>
mysqldump: Got error: 1044: Access denied for user ‘xx’@’xx’ to database ‘xx’ when using LOCK TABLES
查看>>
Mysqldump参数大全(参数来源于mysql5.5.19源码)
查看>>
mysqldump备份时忽略某些表
查看>>
mysqldump实现数据备份及灾难恢复
查看>>
mysqldump数据库备份无法进行操作只能查询 --single-transaction
查看>>
mysqldump的一些用法
查看>>
mysqli
查看>>
MySQLIntegrityConstraintViolationException异常处理
查看>>