Django项目中如何配置使用Redis作为缓存后端?
- 内容介绍
- 文章标签
- 相关推荐
本文共计288个文字,预计阅读时间需要2分钟。
安装 `django-redis` 的最简单方法是使用 `pip`:
bashpip install django-redis==4.7.0
然后在 `settings.py` 中配置缓存后端:
pythonCACHE_BACKEND='django_redis.cache.RedisCache'
django-redis-chs.readthedocs.io/zh_CN/latest/
安装 django-redis 最简单的方法就是用 pip :
pip install django-redis==4.7.0
cache backend 使用配置settings.py
# django缓存配置 CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/9", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } # 存储在缓存中:存储在本机内存中,如果丢失则不能找回,比数据库的方式读写更快。 SESSION_ENGINE = "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "default"
链接redis数据库,原生客户端使用
在某些情况下你的应用需要进入原生 Redis 客户端使用一些 django cache 接口没有暴露出来的进阶特性. 为了避免储存新的原生连接所产生的另一份设置, django-redis 提供了方法get_redis_connection(alias)使你获得可重用的连接字符串.
>>> from django_redis import get_redis_connection >>> con = get_redis_connection("default") >>> con <redis.client.StrictRedis object at 0x2dc4510>
本文共计288个文字,预计阅读时间需要2分钟。
安装 `django-redis` 的最简单方法是使用 `pip`:
bashpip install django-redis==4.7.0
然后在 `settings.py` 中配置缓存后端:
pythonCACHE_BACKEND='django_redis.cache.RedisCache'
django-redis-chs.readthedocs.io/zh_CN/latest/
安装 django-redis 最简单的方法就是用 pip :
pip install django-redis==4.7.0
cache backend 使用配置settings.py
# django缓存配置 CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/9", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } # 存储在缓存中:存储在本机内存中,如果丢失则不能找回,比数据库的方式读写更快。 SESSION_ENGINE = "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "default"
链接redis数据库,原生客户端使用
在某些情况下你的应用需要进入原生 Redis 客户端使用一些 django cache 接口没有暴露出来的进阶特性. 为了避免储存新的原生连接所产生的另一份设置, django-redis 提供了方法get_redis_connection(alias)使你获得可重用的连接字符串.
>>> from django_redis import get_redis_connection >>> con = get_redis_connection("default") >>> con <redis.client.StrictRedis object at 0x2dc4510>

