Loading

django中集成redis

django中集成redis

方式一:通用方案

写一个pool包

import redis
POOL=redis.ConnectionPool(max_connections=1024,decode_responses=True)

再使用的位置导入

conn = Redis(connection_pool=POOL)
res = conn.get('name')

方式二:第三方模块

安装

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",
            "CONNECTION_POOL_KWARGS": {"max_connections": 100}
            # "PASSWORD": "123",
        }
    }
    }

在使用的位置

conn = get_redis_connection()
conn.set.....

第三方模块的好处

一旦配置文件配置 CACHES 后,django的缓存框架(默认是内存),存储的位置也是redis
以后根本不需要会redis的操作,只需要使用 
cache--->django 自带的一个缓存机制
from django.core.cache import cache
cache.set('name',对象)  # 设置键值对
cache.get()  # 取值


'''
强大之处在于不需要关注设置的类型,直接设置就行
把python的对象,通过pickle序列化后,以string形式存到redis中了
'''
posted @ 2022-07-17 16:15  香菜根  阅读(51)  评论(0编辑  收藏  举报