django中使用redis

方式一:

  自己写,使用连接池

  pool.py

import redis
POOL=redis.ConnectionPool(max_connections=10,host="localhost",port=6379)
# 任意位置使用
class TestView(APIView):
    def get(self, requeste):
        conn=redis.Redis(connection_pool=POOL)
        print(conn.get('name'))
        return Response('ok')

方式二

  使用第三方  djagno-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",
            "CONNECTION_POOL_KWARGS": {"max_connections": 100}
            # "PASSWORD": "123",
        }
    }
}
复制代码

  在使用位置

from django_redis import get_redis_connection
conn=get_redis_connection()
print(conn.get('name'))

  一旦这么配置了,以后django的缓存也缓存到reids中了

cache.set('asdfasd','asdfas')

  以后在django中,不用使用redis拿连接操作了,直接用cache做就可以了  

   不需要关注设置的值类型是什么

cache.set('wife',['dlrb','lyf']) # value值可以放任意数据类型

  底层原理,把value通过pickle转成二进制,以redis字符串的形式存到了redis中

  pickle是python独有的序列化和反序列化,只能python玩,把python中所有数据类型都能转成二进制,通过二进制可以在反序列化成功pyhton中的任意对象

posted @   那就凑个整吧  阅读(527)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示