memcache 丢数据解决方案

memcache 丢数据解决方案

  (2011-01-26 12:28:30)
标签: 

memcache

 

丢数据

 

it

分类: 架构与开发
比如一小时以内数据变化都存放到memcached中,无论数据读取或者写入只与memcached交互。但实际情况是,memcached的LRU淘汰算法,把内存分为很多slab, 当某个slab空间已经被使用完了,即使其他slab里面还有空间,仍然存在数据被踢的可能。一小时内,memcached内存占用不到50%,已经能检测到数据丢失。

为了保证数据的完整, memcached 在启动时候应该开启 -M 参数。该参数含义是 return error on memory exhausted (rather than removing items)。看memcached源代码可以知道,开启该参数后,当某个slab写满,新数据将无法写入。保护了原数据不丢失。程序这边如果检测到新数据,就触发把数据回写人数据库的操作,并主动释放一部分内存。

memcached 另外一个问题是,设置了永不过期的数据也会被踢掉,这个问题就得修改memcached 源代码了。

文件 items.c,找到一下代码

for (search = tails[id]; tries > 0 && search != NULL; tries–, search=search->prev) {

if (search->refcount == 0) {

   if (search->exptime == 0 || search->exptime > current_time) {

   itemstats[id].evicted++;

   itemstats[id].evicted_time = current_time – search->time;

   STATS_LOCK();

   stats.evictions++;

   STATS_UNLOCK();

   }

   do_item_unlink(search);

   break;

}

}

修改为:

for (search = tails[id]; tries > 0 && search != NULL; tries–, search=search->prev) {

if (search->refcount == 0 && search->exptime != 0) {

   if (search->exptime > current_time) {

   itemstats[id].evicted++;

   itemstats[id].evicted_time = current_time – search->time;

   STATS_LOCK();

   stats.evictions++;

   STATS_UNLOCK();

   }

   do_item_unlink(search);

   break;

}

}

就是检查队列时候直接跳过过期时间为0的部分,这样保证数据不丢失。修改完毕,重新编译memcache就行。

(ps, 今天发现memcached 1.41版本增加 -N 参数,参数含义为 return error on memory exhausted (allow removing items with expire time > 0, just keep never-expire items), it could)

还有第三种方案是,修改memcached更新数据那部分,发现数据被复写时候,把被覆盖数据挪走。也是要修改源代码。

猜你喜欢

转载自rongdmmap-126-com.iteye.com/blog/1424103