【问题标题】:nginx can't fetch keys from memcahednginx 无法从 memcached 中获取密钥
【发布时间】:2012-10-25 15:44:00
【问题描述】:

问题是 nginx 不获取 memcached 中存在的 memcached 键,每次我请求链接时都会发生这种情况。

memcached 日志:

向 memcached 发出键“site-/links”的 Nginx 请求失败:(但 memcached 中的键数据)

<31 new auto-negotiating client connection
31: Client using the ascii protocol
<31 get site-/links                  ### NO DATA SEND! but it in cache
>31 END
<31 connection closed.

带有“site-/links”键的 Django 请求成功获取数据

<31 get :1:mkey
>31 sending key :1:mkeys 0 4
mval

(dp1
.

>31 END
<31 get :1:site-/links
>31 sending key :1:site-/links         ###data send!
>31 END
<31 set :1:site-/links 0 300 5518
>31 STORED
<31 set :1:mkey 0 300 4
>31 STORED
<31 connection closed.

我的用于 memcached 的 nginx 配置文件:

location / {
default_type  "text/html; charset=utf-8";
set $memcached_key site-$uri;
    memcached_pass 127.0.0.1:11211;
    error_page     404 502 = @django;

}

location @django {
    include uwsgi_params;
    uwsgi_pass unix:///var/tmp/site.sock;
}

django 中间件:

class NginxMemCacheMiddleWare(object):
    def process_response(self, request, response):
        cacheIt = True
        theUrl = request.get_full_path()

        # if it's a GET then store it in the cache:
        if request.method != 'GET':
            cacheIt = False

        # loop on our CACHE_INGORE_REGEXPS and ignore
        # certain urls.
        for exp in settings.CACHE_IGNORE_REGEXPS:
            if re.match(exp,theUrl):
                cacheIt = False

        if cacheIt:
            key = '%s-%s' % (settings.CACHE_KEY_PREFIX,theUrl)
            #key = theUrl
            print "CACHE!"
            print key

            print "MKEY:",cache.get("mkey")
            print cache.get(key)
            cache.set(key,response.content)
            cache.set("mkey","mval")

        return response

那么为什么 nginx 不能使用 memcached 中的键获取数据并且总是转到 django uwsgi 呢?

【问题讨论】:

    标签: django nginx memcached


    【解决方案1】:

    我使用相同的设置,这是一个问题。

    Django 的缓存使用分代缓存,并在密钥生成器中放入前缀。

    你需要做的是确保你 set 来自 django.core.cache.cache._cache

    from django.core.cache import cache
    
    cache._cache.set(...)
    

    为了在我使用 DummyCache 的本地环境中进行这项工作,我将 DummyCache 子类化为属性 _cache,该属性返回自身。

    PS:为荒谬的表现做好准备。我目前受到 100 mb 的出站流量上限的限制。

    【讨论】:

      【解决方案2】:

      从你的 memcached 日志中,你的 nginx 正在做:

      get site-/links
      

      当你的 django 正在做的时候:

      get :1:site-/links
      

      注意:这些不是同一个键,django 的前面有:1:! (:1: 可能由 django 自动添加为一种命名空间)

      换句话说,更改您的 ningx 配置以匹配以下 location-block:

      location / {
        default_type  "text/html; charset=utf-8";
        set $memcached_key :1:site-$uri;
        memcached_pass 127.0.0.1:11211;
        error_page     404 502 = @django;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-11-22
        • 2017-09-29
        • 1970-01-01
        • 2022-01-07
        • 1970-01-01
        • 1970-01-01
        • 2018-03-07
        相关资源
        最近更新 更多