前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >震惊!Django缓存中的数据频频丢失,究竟谁是幕后黑手!

震惊!Django缓存中的数据频频丢失,究竟谁是幕后黑手!

原创
作者头像
Khalil
修改2017-07-26 11:21:52
1.9K1
修改2017-07-26 11:21:52
举报
文章被收录于专栏:Khalil的专栏Khalil的专栏

导语: Django Cache 内容不同步的真相

1.起因

昨天晚上尝试使用celery对Django缓存进行定时任务的更新, 但是发现定时任务并不能刷新到Django中, 由此开始了一阵debug

2.经过

2.1问题出现的场景

想使用一个后台任务在缓存中存放一些信息,然后在Django中有request的时候可以快速获取到页面信息, 但是失败了,用户在进入主页的时候并没有获取到后台任务在缓存中存放的信息

2.2尝试解决问题经过

首先使用celery打出cache对象的内存地址以及一些简单信息

代码逻辑如下

发现和views.py中的打出的cache内存不一

原因: 不同py进程在from django.core.cache import cache中获取的 cache 只是原型的复制品,并不是同一块内存

2.3 解决问题的过程

当然,我们的问题并没有解决,真正的原因是因为我一开始使用的是

代码语言:javascript
复制
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'unique-snowflake',
    }
}

我所使用的 LocMemCache 它的机制是不能做同步缓存的 (*见第三小节)

在更改为DatabaseCache之后,问题解决

代码语言:javascript
复制
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'django_cache',
    }
}

3.结论与文档

废话不多说,直接上官方文档吧:

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:

代码语言:javascript
复制
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 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.起因
  • 2.经过
    • 2.1问题出现的场景
      • 2.2尝试解决问题经过
        • 2.3 解决问题的过程
        • 3.结论与文档
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档