zoukankan      html  css  js  c++  java
  • memcache 缓存失效问题(转)

    在大并发的场合,当cache失效时,大量并发同时取不到cache,会同一瞬间去访问db并回设cache,可能会给系统带来潜在的超负荷风险。

    解决方法

    方法一 
    在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();
            }
        }
    }
  • 相关阅读:
    django从零开始-模板
    django从零开始-模型
    django从零开始-视图
    web基础
    django从零开始-入门
    Pycharm自动添加文件头注释
    django后台密码错误
    module 'sign.views' has no attribute 'search_name'
    TypeError: __init__() got an unexpected keyword argument 't_command'
    pycharm 中的 全局搜索(ctrl+shift+f) 功能无法使用的原因
  • 原文地址:https://www.cnblogs.com/jackluo/p/3726264.html
Copyright © 2011-2022 走看看