如何在 Django 中设置 Memcached 检索超时

How to set Memcached retrieval timeout in Django

如何更改 Django 中 Memcached/Elasticache caching backend 的检索超时?

我正在使用 Amazon 的 Elasticache 在 Django 中缓存内容,我经常看到如下错误:

  File "/usr/local/myproject/.env/lib/python2.7/site-packages/django/template/defaulttags.py", line 285, in render
    return nodelist.render(context)
  File "/usr/local/myproject/.env/lib/python2.7/site-packages/django/template/base.py", line 830, in render
    bit = self.render_node(node, context)
  File "/usr/local/myproject/.env/lib/python2.7/site-packages/django/template/base.py", line 844, in render_node
    return node.render(context)
  File "/usr/local/myproject/.env/lib/python2.7/site-packages/django/templatetags/static.py", line 109, in render
    url = self.url(context)
  File "/usr/local/myproject/.env/lib/python2.7/site-packages/django/contrib/staticfiles/templatetags/staticfiles.py", line 12, in url
    return staticfiles_storage.url(path)
  File "/usr/local/myproject/.env/lib/python2.7/site-packages/django/contrib/staticfiles/storage.py", line 136, in url
    hashed_name = self.cache.get(cache_key)
  File "/usr/local/myproject/.env/lib/python2.7/site-packages/django/core/cache/backends/memcached.py", line 64, in get
    val = self._cache.get(key)
Error: error 31 from memcached_get(myproject:1:staticfiles:27e4bc0): A TIMEOUT OCCURRED

我试过增加我的 Elasticache 集群中的节点数量,但没有效果。我的下一个想法是增加 memcached 检索的超时时间,但 Django docs 似乎没有为此提供选项。

有一个 "TIMEOUT" 选项,但它似乎定义了内容 过期 之后的默认时间,而不是向 memcached 服务器发出 HTTP 请求的超时时间。

django 中没有这样的设置。 像这样的东西应该可以工作,尽管它很脏。确保在创建缓存之前执行以下操作:

import memcached; memcached._SOCKET_TIMEOUT = whatever_you_want_it_to_be;

我采用的解决方案是将我的 Django 缓存后端切换到 django-ft-cache,这是标准内存缓存后端的 fault-tolerant 版本。所以现在,当发生周期性超时时,缓存只是绕过 non-cache 媒体检索,而不是抛出 500 错误。