【发布时间】:2014-10-11 18:25:13
【问题描述】:
我正在尝试创建一个缓存流,在用户请求时它会缓存一个包含 870 条记录的大字典,并且它应该在缓存中保留一段时间。当定义的时间通过下一个请求时,字典应该在缓存内存中更新。
所以我创建了这样一个函数:
from django.core.cache import get_cache
def update_values_mapping():
cache_en = get_cache('en')
values_dict = get_values_dict() <- this make a request to obtain the dict with values
cache_en.set_many(values_dict, 120) # 120s for testing
cache_en.set('expire', datetime.datetime.now() + datetime.timedelta(seconds=120))
然后在第二个函数中我尝试从缓存中获取值
from django.core.cache import get_cache
def get_value_details(_id):
cache = get_cache('en')
details = cache.get(_id, {}) # Values in cache has expire date so they should eventually be gone
expire = cache.get('expire', None)
if not details and expire and expire < datetime.now():
update_values_mapping()
value = cache.get(_id, {})
return details
在渲染视图时,会多次调用 get_value_details() 来获取所有需要的值。
问题是缺少某些值,例如cache.get('b', {}) return {} 即使值 'b' 已保存到缓存(并且到期日期尚未过去)。缺失值在变化,有时是“a”,有时是“b”,有时是“c”等。
到目前为止,我一直在 LocMemCache 和 DummyCache 上对其进行测试。 我的示例缓存设置:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'cache-default'
},
'en': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'cache-en'
},
'pl': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'cache-pl'
}
}
当我在控制台中使用它时,一些值在下次调用 update_values_mapping() 后从缓存中消失了,但有些从一开始就丢失了。
有没有人知道它可能是什么? 或者也许如何以另一种方式解决描述的流程?
【问题讨论】: