【问题标题】:Redis cache not working with djangoRedis缓存不适用于django
【发布时间】:2015-05-29 10:40:38
【问题描述】:

我在 ubuntu EC2 节点上有一个 django 项目,我想设置一个缓存,我正在关注 http://michal.karzynski.pl/blog/2013/07/14/using-redis-as-django-session-store-and-cache-backend/ 以使用 redis。在文章中作者参考https://docs.djangoproject.com/en/1.7/topics/cache/,基于此我可以做到:

(env1)ubuntu@ip-172-31-22-65:~/projects/tp$ python manage.py shell
Python 3.4.0 (default, Apr 11 2014, 13:05:11)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import django
>>> import redis
>>> from django.core.cache import cache
>>> cache.set('my_key','hi world')
>>> cache.get('my_key')
'hi world'

我当前的 django 视图包含;

def index(token):

    html = calculator(token)
    print('here1')

    import redis
    from django.core.cache import cache
    cache.set('my_key', 'hello, world!', 60*60*12)
    print('here2')

    return html

但是,当我触发索引功能时,没有任何内容保存到缓存中。我从命令行检查后。

如何让缓存工作?

编辑:

>>> print(settings.CACHES)
{'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}

【问题讨论】:

  • 你的缓存设置是什么样的?
  • “导入redis”的目的是什么?您在下面不使用它,因此正如 Daniel 所说,您的缓存设置很重要。在 shell 和你的索引函数中打印它
  • 从 django.conf 导入设置打印 settings.CACHES
  • 我已经删除了“import redis”,请查看编辑
  • 好的,您正在使用 LocMemCache 后端,这意味着您正在使用 Python 进程的内存来缓存数据。这也意味着您的数据将在进程终止后立即丢失。这也意味着你没有使用 Redis

标签: python django caching redis


【解决方案1】:

关键是你的CACHES配置,应该是:

CACHES = {
    'default': {
        'BACKEND': 'redis_cache.RedisCache',
        'LOCATION': '/var/run/redis/redis.sock',
    },
}

(参见http://michal.karzynski.pl/blog/2013/07/14/using-redis-as-django-session-store-and-cache-backend/

【讨论】:

  • 如果您按照本页前面的步骤进行操作
  • 谢谢,我会修改的。您所说的“在 Django 索引函数中无法从 shell 获取一个缓存值”是什么意思?
  • 我假设您一方面使用的是正在运行的 Django 实例,另一方面使用的是 Django shell(两者同时),在这种情况下,它是 2 个不同的进程 不同的内存空间,不同的缓存:)
  • 是的,我同时运行它们。如果不是同一个缓存,如何在命令行测试?
  • 确切地说,您需要一个在进程之间“共享”的外部进程。使用 Redis,你会得到这个。您可以使用 Memcache 实现相同的目标(它更“经典”并且易于在 django 中设置为后端)。
【解决方案2】:

Raphaël Braud 答案的更新版本:

 'default': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'LOCATION': '/var/run/redis/redis.sock',
    },

【讨论】:

    猜你喜欢
    • 2018-02-13
    • 2014-03-22
    • 2018-11-09
    • 2017-01-24
    • 2015-08-07
    • 1970-01-01
    • 2017-09-28
    • 2020-01-27
    • 2014-08-05
    相关资源
    最近更新 更多