本文共 1829 字,大约阅读时间需要 6 分钟。
在不考虑redis实现方式的情况下,我们自己手动设计一个删除有时间限制的key有几种策略?
定时删除:在创建完一个key时,同时创建一个定时任务,监听key是否过期。
定期删除:设置好周期之后,间断性的扫描key,然后删除过期的key。(这里的扫描方式拓展开来也可以划分为全部扫还是随机部分扫,随机的发方式又可以怎样设计)
惰性删除:联想ThreadLocal的实现方式。前两两个都是主动去做删除,那如果我喜欢被动,在条件允许的情况下,可以要用时做一个判断,if(过期)then(删除)。
再来考虑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/