Memcached expire 设置错误引起的set(key,exp,value)为true而get(key)为null的问题

与作者遇到相同问题所以转载了此文章,以为设置的时间是毫秒!

最近项目中使用到了Memcached,而客户端选择了XMemcached ,在设置过期时间时,因对Memcached 不熟悉,将expire 设置为1000000000,本意表示尽量长的时间不要过期,但在测试时发现,memcachedClient.set(key,exp,value)结 果返回true,即代表该项已成功存入缓存,但当调用memcachedClient.get(key)时始终返回为null,起初以为key的生成策略 有误,后来当把exp填了个1000时,Memcached的set 和 get方法均返回true,看来问题出在expire,所以查了下文档,发现Memcached默认expire为0即代表永不过期,而这个过期时间最长 为30天= 30*24*60*60 = 2592000秒,所以又将expire配置为2592000秒,发现正常执行,为了测试Memcached是否为最长30天,又将该值加了1变成 2592001,此时出现了和开始一样的错误,set返回 true,但get返回为null,这样应该映证了30长最长时间的猜想。而这个时间应该是Memcached本身设置的,经过查找发现 Memcached源码memcached.c里边有如下代码。注意第一行 #define REALTIME_MAXDELTA 60*60*24*30 即为30天。

  1. #define REALTIME_MAXDELTA 60*60*24*30  
  2.   
  3. /* 
  4.  * given time value that's either unix time or delta from current unix time, return 
  5.  * unix time. Use the fact that delta can't exceed one month (and real time value can't 
  6.  * be that low). 
  7.  */  
  8. static rel_time_t realtime(const time_t exptime) {  
  9.     /* no. of seconds in 30 days - largest possible delta exptime */  
  10.   
  11.     if (exptime == 0) return 0; /* 0 means never expire */  
  12.   
  13.     if (exptime > REALTIME_MAXDELTA) {  
  14.         /* if item expiration is at/before the server started, give it an 
  15.            expiration time of 1 second after the server started. 
  16.            (because 0 means don't expire).  without this, we'd 
  17.            underflow and wrap around to some large value way in the 
  18.            future, effectively making items expiring in the past 
  19.            really expiring never */  
  20.         if (exptime <= process_started)  
  21.             return (rel_time_t)1;  
  22.         return (rel_time_t)(exptime - process_started);  
  23.     } else {  
  24.         return (rel_time_t)(exptime + current_time);  
  25.     }  
  26. }  

XMemcached是一个新java memcached client。Memcached 是一个高性能的分布式内存对象的key-value缓存系统,用于动态Web应用以减轻数据库负载,
现在也有很多人将它作为内存式数据库在使用,memcached通过它的自定义协议与客户端交互,而XMemcached就是它的一个java客户端实现。

关于XMemcached详细说明,参考XMemcached简介

转自:http://blog.csdn.net/shixing_11/article/details/7059643

猜你喜欢

转载自hyl198611.iteye.com/blog/1985821