导语: Django Cache 内容不同步的真相
昨天晚上尝试使用celery对Django缓存进行定时任务的更新, 但是发现定时任务并不能刷新到Django中, 由此开始了一阵debug
想使用一个后台任务在缓存中存放一些信息,然后在Django中有request的时候可以快速获取到页面信息, 但是失败了,用户在进入主页的时候并没有获取到后台任务在缓存中存放的信息
首先使用celery打出cache对象的内存地址以及一些简单信息
代码逻辑如下
发现和views.py中的打出的cache内存不一
原因: 不同py进程在from django.core.cache import cache
中获取的 cache 只是原型的复制品,并不是同一块内存
当然,我们的问题并没有解决,真正的原因是因为我一开始使用的是
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'unique-snowflake',
}
}
我所使用的 LocMemCache
它的机制是不能做同步缓存的 (*见第三小节)
在更改为DatabaseCache
之后,问题解决
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'django_cache',
}
}
废话不多说,直接上官方文档吧:
Local-memory caching
This is the default cache if another is not specified in your settings file. If you want the speed advantages of in-memory caching but don’t have the capability of running Memcached, consider the local-memory cache backend. This cache is per-process (see below) and thread-safe. To use it, set BACKEND to “django.core.cache.backends.locmem.LocMemCache”. For example:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'unique-snowflake',
}
}
The cache LOCATION is used to identify individual memory stores. If you only have one locmem cache, you can omit the LOCATION; however, if you have more than one local memory cache, you will need to assign a name to at least one of them in order to keep them separate.
Note that each process will have its own private cache instance, which means no cross-process caching is possible. This obviously also means the local memory cache isn’t particularly memory-efficient, so it’s probably not a good choice for production environments. It’s nice for development.
着重标记最后一段文档:
Note that each process will have its own private cache instance, which means no cross-process caching is possible. 注意每个进程都有自己的私有缓存实例,这意味着不可能有跨进程缓存
所以说,LocMemCache是不能用来做同步缓存的! 请使用别的任意Cache!
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。