【问题标题】:redis not connected with django-redisredis 没有与 django-redis 连接
【发布时间】:2015-09-21 10:50:33
【问题描述】:

我在我的缓存中设置了一个查询集:

cache.set('person',Lecture_Detail.objects.all())

在我看来:

from django.core.cahe import cache
t3=datetime.datetime.now()
list(Lecture_Detail.objects.all())
t5 = datetime.datetime.now()
print "time before",(t5 - t3)
g = cache.get('person')
t4 = datetime.datetime.now()
print "time after",(t4 - t5)
g = cache.get('person')
t6 = datetime.datetime.now()
print "time after",t6-t4
g = cache.get('person')
t7 = datetime.datetime.now()
print "time after",t7-t6

当我执行它时,它的输出是:

time before 0:00:00.014256
time after 0:00:01.366022
time after 0:00:01.552436
time after 0:00:01.433049

所以我认为我的 redis 与 django-redis 无关。 我的设置是:

CACHES = {
    "default": {
        "BACKEND": "redis_cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379:1",
        "OPTIONS": {
            "CLIENT_CLASS": "redis_cache.client.DefaultClient",
        }
    }
}

所以请我提前给我一些建议..thanx..

【问题讨论】:

  • 你在哪里运行你的 Redis 实例?同一台服务器还是其他地方? queryset 是一次性加载还是懒惰? (即:它是获取所有行还是仅在您读取行时获取行?)。差别有多大?您可以编辑您的问题以包含这些问题的答案。

标签: python django django-redis


【解决方案1】:

当你写queryset=Lecture_Detail.objects.all()时,数据库sql查询还没有执行。 查询执行时:

  1. 迭代
  2. 切片
  3. 酸洗/缓存
  4. repr()
  5. len()
  6. 列表()
  7. bool()

在此处了解更多信息:When QuerySets are evaluated。因此,在您的示例中,数据库查询将在行 cache.set('person',queryset)

上执行

您可以通过将queryset=Lecture_Detail.objects.all()更改为list(queryset=Lecture_Detail.objects.all())进行测试

【讨论】:

  • 正如你现在建议我的那样,我在两种情况下都应用以下操作(在从数据库和缓存中获取数据之后):t1=datetime.datetime.now() g = Lecture_Detail.objects.all () name = g.filter(lecture_name = 'Chemistry') length = len(name) t2=datetime.datetime.now() bt 仍然时差很大:“没有缓存 0:00:00.903429 有缓存 0 :00:02.490702 " 所以请给我一些建议..
  • 表中有多少条记录?过滤后有多少条记录?
  • 表中有101006条记录,过滤后有50000条
  • 我自己试过,但我使用了文件系统缓存,得到了类似的结果:没有缓存 0:00:00.246513 和 wich 缓存 0:00:00.666614
【解决方案2】:

实际上我的错误是我使用 django 缓存而不是使用 redis 缓存....要使用 redis,我们必须这样做:

首先从您的 python shell 中设置数据或查看为:

import redis
r=redis.StrictRedis()
r.set('person',Lecture_Detail.objects.all())

从redis缓存中获取数据:

import redis

r=redis.StrictRedis()
t3=datetime.datetime.now()
list(Lecture_Detail.objects.all())
t5 = datetime.datetime.now()
print "time before",(t5 - t3)
g = r.get('person')
t4 = datetime.datetime.now()
print "time after",(t4 - t5)

现在的时差简直令人难以置信

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-06
    • 2021-02-25
    • 2021-12-14
    • 1970-01-01
    • 2020-06-29
    • 1970-01-01
    • 2022-11-07
    • 2019-01-22
    相关资源
    最近更新 更多