写入Django缓存非常慢 [英] Very slow to write to Django cache

查看:79
本文介绍了写入Django缓存非常慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经将数据库查询缓存在全局变量中,以加快我的应用程序的速度.由于这是极不建议的做法(确实会产生问题),因此我想改用任何一种Django缓存.我尝试了LocMemCache和DatabaseCache,但两者都花了大约 15秒来设置我的变量(比生成数据所需的时间长两倍,即大小为7MB).

I used to cache a database query in a global variable to speed up my application. Since this is strongly unadvised (and it did generate problems), I want to use any kind of Django cache instead. I tried LocMemCache and DatabaseCache, but both take... about 15 seconds to set my variable (twice longer than it take to generate the data, which is 7MB in size).

这是预期的吗?我做错什么了吗?

Is that expected ? Am I doing something wrong ?

(Memcached的大小限制为1MB,我无法拆分包含任意大二进制掩码的数据).

(Memcached is limited to 1MB, and I cannot split my data, which consists in arbitrarily big binary masks).

FileBasedCache设置也需要30秒.

Settings.py:

Settings.py:

CACHES = {
    'default': {...},
    'stats': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 
        # or 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'stats',
    },
}

Service.py:

Service.py:

from django.core.cache import caches

def stats_service():
    stats_cache = caches['stats']
    if stats_cache.get('key') is None:
        stats_cache.set('key', data)  # 15s with DatabaseCache, 30s with LocMemCache
    return stats_cache.get('key')

全局变量(超快速)版本:

Global variable (super fast) version:

_cache = {}

def stats_service():
    if _cache.get('key') is None:
        _cache['key'] = data
    return _cache['key']

推荐答案

此代码段实际上可以正常工作: https://djangosnippets.org/snippets/2396/

This snippet actually works fine: https://djangosnippets.org/snippets/2396/

据我了解,使用全局变量进行缓存的唯一问题是线程安全性,而且这个无棘手的版本是线程安全的.

As I understood, the only problem with using global variables for caching is thread safety, and this no-pickle version is thread-safe.

这篇关于写入Django缓存非常慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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