django

django缓存与redis

2018-09-21  本文已影响0人  Python野路子

什么是缓存

缓存系统是为了解决数据库服务器和web服务器之间的瓶颈。如果一个网站的流量很大,这个瓶颈将会非常明显,每次数据库查询耗费的时间将会非常可观。对于更新速度不是很快的网站,我们可以用静态化来避免过多的数据库查询。对于更新速度以秒计的网站,静态化也不会太理想,可以用缓存系统来构建。如果只是单台服务器用作缓存,问题不会太复杂,如果有多台服务器用作缓存,就要考虑缓存服务器的负载均衡。

什么是redis

安装操作:

在django中使用redis当作缓存

pip install django-redis
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}
from django.views.decorators.cache import cache_page
...
url(r'^login/$', cache_page(60)(views.Login.as_view()), name="login"),
from django.core.cache import cache
cache.set('my_key', 'hello, world!', 30)
cache.add('my_key', 'hello, world!')
cache.set_many({'a': 1, 'b': 2, 'c': 3})
cache.get('add_key')
cache.get_or_set("test", "2", 100)
cache.delete('a')
cache.delete_many(['a', 'b', 'c'])
cache.clear()
上一篇 下一篇

猜你喜欢

热点阅读