memcache 缓存失效问题(转)
2014-05-13 19:19
369 查看
在大并发的场合,当cache失效时,大量并发同时取不到cache,会同一瞬间去访问db并回设cache,可能会给系统带来潜在的超负荷风险。
在load db之前先add一个mutex key, mutex key add成功之后再去做加载db, 如果add失败则sleep之后重试读取原cache数据。为了防止死锁,mutex key也需要设置过期时间。伪代码如下
解决方法
方法一在load db之前先add一个mutex key, mutex key add成功之后再去做加载db, 如果add失败则sleep之后重试读取原cache数据。为了防止死锁,mutex key也需要设置过期时间。伪代码如下
if (memcache.get(key) == null) { // 3 min timeout to avoid mutex holder crash if (memcache.add(key_mutex, 3 * 60 * 1000) == true) { value = db.get(key); memcache.set(key, value); memcache.delete(key_mutex); } else { sleep(50); retry(); } } 方法二 在value内部设置1个超时值(timeout1), timeout1比实际的memcache timeout(timeout2)小。当从cache读取到timeout1发现它已经过期时候,马上延长timeout1并重新设置到cache。然 后再从数据库加载数据并设置到cache中。伪代码如下 v = memcache.get(key); if (v == null) { if (memcache.add(key_mutex, 3 * 60 * 1000) == true) { value = db.get(key); memcache.set(key, value); memcache.delete(key_mutex); } else { sleep(50); retry(); } } else { if (v.timeout <= now()) { if (memcache.add(key_mutex, 3 * 60 * 1000) == true) { // extend the timeout for other threads v.timeout += 3 * 60 * 1000; memcache.set(key, v, KEY_TIMEOUT * 2); // load the latest value from db v = db.get(key); v.timeout = KEY_TIMEOUT; memcache.set(key, value, KEY_TIMEOUT * 2); memcache.delete(key_mutex); } else { sleep(50); retry(); } } }
相关文章推荐
- PHP使用Memcache时模拟命名空间及缓存失效问题的解决
- memcache应对缓存失效问题
- redis和memcache缓存击穿,缓存失效问题
- PHP使用Memcache时模拟命名空间及缓存失效问题的解决
- Memcache关于缓存失效时间的问题
- memcache 缓存失效问题
- 一个Memcache+Hibernate自处理二级缓存问题
- 解决服务器缓存失效后可能导致的雪崩问题(thinkphp为例)
- php缓存扩展频繁存储/读取数组引发CPU过高问题排查手记(php-memcache为例)
- memcached缓存失效时的高并发访问问题解决
- php无法加载Memcache缓存模块问题及Memcache的安装
- 缓存击穿、失效及热点key问题
- memcached缓存失效时的高并发访问问题解决
- 简单处理K->V缓存失效后高并发访问导致数据库负载急剧上升的问题
- 使用 Retrofit 和 okhttp 强制缓存失效问题
- spring boot整合shiro后,部分注解(Cache缓存、Transaction事务等)失效的问题
- Hibernate 二级缓存 失效问题!!!
- 多应用共享memcache缓存带来的问题
- GDI+中启动双缓存后缩放失效的问题
- 功能测试--H5页面发红包的隐藏问题(缓存、缓存失效以及失效的后续处理)