1.说明redis作为一个缓存数据库,在各方面都有很大作用,python支持操作redis,如果你使用django,有一个专为django搭配的redis库,即django-redis
2.安装pip install django-redis
3.配置3.1 配置redis打开django的配置文件,比如说setting.py,里面设置caches项
caches = { "default": { "backend": "django_redis.cache.rediscache", "location": "redis://127.0.0.1:6379/1", "options": { "client_class": "django_redis.client.defaultclient", } }}
一个caches里可以配置多个redis连接信息,每一个都有自己的别名(alias),上面的“default”就是别名,到时候可以通过不同别名连接不同redis数据库
location是连接的信息,包括ip端口用户密码等,如果不需要用户密码则可以省略不写,django-redis支持三种连接协议,如下
协议说明举例
redis:// 普通的tcp套接字连接 redis://[[username]:[password]]@localhost:6379/0
rediss ssl方式的tcp套接字连接 rediss://[[username]:[password]]@localhost:6379/0
rediss:// unix域套接字连接 unix://[[username]:[password]]@/path/to/socket.sock?db=0
3.2 使用redis存储sessiondjango默认的session是存储在sql数据库里的,但我们都知道普通的数据会被数据存储在硬盘上,速度没有那么快,如果想改成存储在redis里,只需要在配置文件里配置一下就行
session_engine = "django.contrib.sessions.backends.cache"session_cache_alias = "default"
3.3 redis连接超时时间设置连接超时的秒数可以在配置项里指定,socket_connect_timeout表示连接redis的超时时间,socket_timeout表示使用redis进行读写操作的超时时间
caches = { "default": { # ... "options": { "socket_connect_timeout": 5, # 连接redis超时时间,单位为秒 "socket_timeout": 5, # redis读写操作超时时间,单位为秒 } }}
4.使用redis4.1 使用默认redis如果你想使用默认的redis,也就是在配置文件里设置的别名为“default”的redis,可以引用django.core.cache里的cache
from django.core.cache import cachecache.set("name", "冰冷的希望", timeout=none)print(cache.get("name"))
4.2 使用指定redis(原生redis)当你在配置文件里写了多个redis连接,可以通过别名指定要使用哪个redis
from django_redis import get_redis_connectionredis_conn = get_redis_connection("chain_info")redis_conn.set("name", "icy_hope")print(redis_conn.get("name"))
要注意,通过get_redis_connection()获取得到的客户端是原生redis客户端,虽然基本上支持所有的原生redis命令,但它返回的数据是byte类型,你需要自己decode
5.连接池使用连接池的好处是不用管理连接对象,它会自动创建一些连接对象并且尽可能重复使用,所以相当来说性能会好一点
5.1 配置连接池要使用连接池,首先要在django的配置文件里写上连接池的最大连接数
caches = { "default": { "backend": "django_redis.cache.rediscache", ... "options": { "connection_pool_kwargs": {"max_connections": 100} } }}
5.2 使用连接池我们可以通过连接别名确定要使用哪个redis,然后正常执行命令就行,我们不用在乎它创建了哪些连接实例,但你可以通过connection_pool的_created_connections属性查看当前创建了多少个连接实例
from django_redis import get_redis_connectionredis_conn = get_redis_connection("default")redis_conn.set("name", "冰冷的希望")print(redis_conn.get("name"))# 查看目前已创建的连接数量connection_pool = redis_conn.connection_poolprint(connection_pool._created_connections)
5.3 自定义连接池django-redis默认的连接的类是defaultclient,如果你有更高的定制需求,可以新建一个自己的类,继承connectionpool
from redis.connection import connectionpoolclass mypool(connectionpool): pass
有了这个类之后还需要在django的配置文件里指定它
"options": { "connection_pool_class": "xxx.xxx.mypool",}
以上就是django redis怎么使用的详细内容。