1

问题是 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 呢?

4

2 回答 2

0

from your memcached logs, your nginx is doing:

get site-/links

while your django is doing:

get :1:site-/links

Note: those are not the same keys, the django one has :1: in front! (the :1: is propably added automatically by django as a sort of namespace)

In other words change your ningx config to match the following 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;
}
于 2012-11-05T20:00:08.957 回答
0

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

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

您需要做的是确保您setdjango.core.cache.cache._cache<-- 内部 memcached 绑定。

from django.core.cache import cache

cache._cache.set(...)

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

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

于 2012-11-05T20:12:59.123 回答