设为首页 收藏本站
查看: 1088|回复: 0

[经验分享] redis主从之过期key判断

[复制链接]

尚未签到

发表于 2015-7-21 11:22:01 | 显示全部楼层 |阅读模式
  大家在使用redis的时候,经常会用expire来设置key的过期时间,之前一直用的很high,以为某个key到期就会马上清除。如果只是在单个redis(即一个主redis)下是没有问题的。但是在主从redis中下面的用法就有问题鸟。
  



1
  这样设置了redis的key与过期时间,然后想通过这种方式来做判断的得注意了。



1
  运行之后发现,redis的key还在,值当然也在了。不过ttl的值为-1,说明该key已经过期了,但是key为啥还存在呢?
  请看下面解释。
  

redis如何删除过期数据




      随着nosql风潮兴起,redis作为当中一个耀眼的明星,也越来越多的被关注和使用,我在工作中也广泛的用到了redis来充当cache和key-value DB,但当大家发现数据越来越多时,不禁有些担心,redis能撑的住吗,虽然官方已经有漂亮的benchmark,自己也可以做做压力测试,但是看看源码,也是确认问题最直接的办法之一。比如目前我们要确认的一个问题是,redis是如何删除过期数据的?       用一个可以"find reference"的IDE,沿着setex(Set the value and expiration of a key)命令一窥究竟:
  



1 void setexCommand(redisClient *c) {
2     c->argv[3] = tryObjectEncoding(c->argv[3]);
3     setGenericCommand(c,0,c->argv[1],c->argv[3],c->argv[2]);
4 }
  
      setGenericCommand是一个实现set,setnx,setex的通用函数,参数设置不同而已。
  





1 void setCommand(redisClient *c) {
2     c->argv[2] = tryObjectEncoding(c->argv[2]);
3     setGenericCommand(c,0,c->argv[1],c->argv[2],NULL);
4 }
5  
6 void setnxCommand(redisClient *c) {
7     c->argv[2] = tryObjectEncoding(c->argv[2]);
8     setGenericCommand(c,1,c->argv[1],c->argv[2],NULL);
9 }
10  
11 void setexCommand(redisClient *c) {
12     c->argv[3] = tryObjectEncoding(c->argv[3]);
13     setGenericCommand(c,0,c->argv[1],c->argv[3],c->argv[2]);
14 }
  
      再看setGenericCommand:






1 void setGenericCommand(redisClient *c, int nx, robj *key, robj *val, robj *expire) {
2     long seconds = 0; /* initialized to avoid an harmness warning */
3
4     if (expire) {
5         if (getLongFromObjectOrReply(c, expire, &seconds, NULL) != REDIS_OK)
6             return;
7         if (seconds db,key) != NULL && nx) {
14         addReply(c,shared.czero);
15         return;
16     }
17     setKey(c->db,key,val);
18     server.dirty++;
19     if (expire) setExpire(c->db,key,time(NULL)+seconds);
20     addReply(c, nx ? shared.cone : shared.ok);
21 }
  
       13行处理"Set the value of a key, only if the key does not exist"的场景,17行插入这个key,19行设置它的超时,注意时间戳已经被设置成了到期时间。这里要看一下redisDb(即c->db)的定义:





typedef struct redisDb {
dict *dict;                 /* The keyspace for this DB */
dict *expires;              /* Timeout of keys with a timeout set */
dict *blocking_keys;        /* Keys with clients waiting for data (BLPOP) */
dict *io_keys;              /* Keys with clients waiting for VM I/O */
dict *watched_keys;         /* WATCHED keys for MULTI/EXEC CAS */
int id;
} redisDb;
  
        仅关注dict和expires,分别来存key-value和它的超时,也就是说如果一个key-value是有超时的,那么它会存在dict里,同时也存到expires里,类似这样的形式:dict[key]:value,expires[key]:timeout.
  当然key-value没有超时,expires里就不存在这个key。剩下setKey和setExpire两个函数无非是插数据到两个字典里,这里不再详述。
  
       那么redis是如何删除过期key的呢。
       通过查看dbDelete的调用者,首先注意到这一个函数,是用来删除过期key的。
  





1 int expireIfNeeded(redisDb *db, robj *key) {
2     time_t when = getExpire(db,key);
3
4     if (when < 0) return 0; /* No expire for this key */
5
6     /* Don't expire anything while loading. It will be done later. */
7     if (server.loading) return 0;
8
9     /* If we are running in the context of a slave, return ASAP:
10      * the slave key expiration is controlled by the master that will
11      * send us synthesized DEL operations for expired keys.
12      *
13      * Still we try to return the right information to the caller,
14      * that is, 0 if we think the key should be still valid, 1 if
15      * we think the key is expired at this time. */
16     if (server.masterhost != NULL) {
17         return time(NULL) > when;
18     }
19
20     /* Return when this key has not expired */
21     if (time(NULL) expires);
16             time_t now = time(NULL);
17
18             expired = 0;
19             if (num > REDIS_EXPIRELOOKUPS_PER_CRON)
20                 num = REDIS_EXPIRELOOKUPS_PER_CRON;
21             while (num--) {
22                 dictEntry *de;
23                 time_t t;
24
25                 if ((de = dictGetRandomKey(db->expires)) == NULL) break;
26                 t = (time_t) dictGetEntryVal(de);
27                 if (now > t) {
28                     sds key = dictGetEntryKey(de);
29                     robj *keyobj = createStringObject(key,sdslen(key));
30
31                     propagateExpire(db,keyobj);
32                     dbDelete(db,keyobj);
33                     decrRefCount(keyobj);
34                     expired++;
35                     server.stat_expiredkeys++;
36                 }
37             }
38         } while (expired > REDIS_EXPIRELOOKUPS_PER_CRON/4);
39     }
40 }
41
  
        这个函数的意图已经有说明:删一点点过期key,如果过期key较少,那也只用一点点cpu。25行随机取一个key,38行删key成功的概率较低就退出。这个函数被放在一个cron里,每毫秒被调用一次。这个算法保证每次会删除一定比例的key,但是如果key总量很大,而这个比例控制的太大,就需要更多次的循环,浪费cpu,控制的太小,过期的key就会变多,浪费内存——这就是时空权衡了。
  
       最后在dbDelete的调用者里还发现这样一个函数:
  


/* This function gets called when 'maxmemory' is set on the config file to limit
* the max memory used by the server, and we are out of memory.
* This function will try to, in order:
*
* - Free objects from the free list
* - Try to remove keys with an EXPIRE set
*
* It is not possible to free enough memory to reach used-memory < maxmemory
* the server will start refusing commands that will enlarge even more the
* memory usage.
*/
void freeMemoryIfNeeded(void)        这个函数太长就不再详述了,注释部分说明只有在配置文件中设置了最大内存时候才会调用这个函数,而设置这个参数的意义是,你把redis当做一个内存cache而不是key-value数据库。
        以上3种删除过期key的途径,第二种定期删除一定比例的key是主要的删除途径,第一种“读时删除”保证过期key不会被访问到,第三种是一个当内存超出设定时的暴力手段。由此也能看出redis设计的巧妙之处。
       这下知道为啥从从redis中能访问到过期的key了,虽然从redis知道key过期,但没有权限删除。
       以上纯属自己的理解,有什么不对,请批评指正。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-89025-1-1.html 上篇帖子: Redis 的安装配置介绍 下篇帖子: Jedis操作redis的例子
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表