Redis主从模式下从库过期的key仍然能够被读到的解决方案

更新时间:2023-06-25 18:48:25 阅读: 评论:0

Redis主从模式下从库过期的key仍然能够被读到的解决⽅案⼤家在使⽤redis的时候,经常会⽤expire来设置key的过期时间,以为某个key到期就会马上清除。如果只是在单个redis(即⼀个主redis)下是没有问题的。但是如果为了实现读写分离,搭建了主从服务器,那么就会遇上从库Key不失效的问题了。(使⽤Redis3.2以后版本的同学请忽略,3.2之后的版本已不存在以下问题)
场景重现:
徜徉造句主: tex name 20 Johny
高中生成语
从:
广式炒饭get name >> Johny
ttl name >> 18
// 过了⼀分钟...
递造句
// 发现name这个key已经失效了
火才
ttl name >> -1
get name >> Johny  // 仍然能获取到key的值
主:get  name >> nil // 主Redis服务器上获取不到
从:get name >> nil // 此时,从Redis服务器上也获取不到了
Redis key的三种过期策略
惰性删除:当读/写⼀个已经过期的key时,会触发惰性删除策略,直接删除掉这个过期key,很明显,这是被动的!
定期删除:由于惰性删除策略⽆法保证冷数据被及时删掉,所以 redis 会定期主动淘汰⼀批已过期的key。(在第⼆节中会具体说明)
主动删除:当前已⽤内存超过maxMemory限定时,触发主动清理策略。主动设置的前提是设置了maxMemory的值
Redis删除过期Key的源码
int expireIfNeeded(redisDb *db, robj *key) {
time_t when = getExpire(db,key);
if (when < 0) return 0; /* No expire for this key */
/* Don't expire anything while loading. It will be done later. */    if (rver.loading) return 0;
/* If we are running in the context of a slave, return ASAP:
* the slave key expiration is controlled by the master that will      * nd 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 (rver.masterhost != NULL) {
return time(NULL) > when;
小城市}
/* Return when this key has not expired */
if (time(NULL) <= when) return 0;
/* Delete the key */
rver.stat_expiredkeys++;
propagateExpire(db,key);
return dbDelete(db,key);
腌制生姜}腊八粥作者

本文发布于:2023-06-25 18:48:25,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/89/1054662.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:删除   策略   惰性   设置   服务器   搭建   问题
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图