缓存随机删除项目 [英] Cache randomly removing items

查看:179
本文介绍了缓存随机删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设置了一个简单的本地内存缓存,我使用这样:

I set up a simple local memory cache that I use like this:

from django.core.cache import caches

def stats_service(db):
    stats_cache = caches['stats']
    if stats_cache.get(db) is None:
        stats_cache.set(db, GlobalStatsService(db))
    return stats_cache.get(db)

服务器运行后,我通过一个视图调用这个函数,在命令行上卷曲,来初始化缓存。

After the server is running, I call this function through a view, with a curl on the command-line, to initialize the cache.

问题是如果我打了几次,有时候将找到该项并立即返回值,如预期的,有时不会找到它,并将重新计算该值。键(这里 db )是我希望它们的字符串。我不明白为什么项目从缓存中删除,显然是随机的,以及如何使它们保持。

The problem is that if I call it several times, sometimes it will find the item and return the value immediately, as expected, and sometimes will not find it and will recalculate the value. The keys (here db) are the strings I expect them to be. I cannot understand why items are dropped from the cache, apparently randomly, and how to make them stay.

有趣的是,当我使用全局变量时,行为是一样的Django的缓存框架(由于1MB的限制,我尝试过除了memcached之外)

Interestingly, the behavior was the same when I was using global variables instead of Django's cache framework (and I tried them all except memcached because of the 1MB limitation).

我没有设置 TIMEOUT value(显然全局变量版本也没有):

I have set no TIMEOUT value (and obviously the global variables version had none either):

CACHES = {
    ...
    'stats': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'stats',
    },

我的应用程序运行Apache和mod_wsgi,2进程和4线程。也许是相关的可能是不同的进程访问自己的缓存版本?

My app runs with Apache and mod_wsgi, 2 processes and 4 threads. Maybe it is related. Could it be that a different process accesses its own version of the cache ?

我做错了什么?

推荐答案

是的,这正是发生了什么。本地内存缓存正是这样的:本地进程。

Yes, that is precisely what is happening. The local memory cache is exactly that: local to the process.

它不是真的适合在生产中使用,绝对不适用于多进程环境。使用适当的缓存后端; Redis的例子很简单,起床和运行。

It is not really suitable for use in production, and definitely not in a multi-process environment. Use a proper cache backend; Redis for example is very simple to get up and running.

这篇关于缓存随机删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆