django-redis和redis连接

redis连接

安装

pip install redis

 

简单连接

  1. import redis
  2. # 直接连接redis
  3. conn = redis.Redis(host='ip地址', port=6379, password='密码', encoding='utf-8')
  4. # 设置键值:aaa="9999" 且超时时间为10秒(值写入到redis时会自动转字符串)
  5. conn.set('aaa', 9999, ex=10)
  6. # 根据键获取值:如果存在获取值(获取到的是字节类型);不存在则返回None
  7. value = conn.get('aaa')
  8. print(value)

上面python操作redis的示例是以直接创建连接的方式实现,每次操作redis如果都重新连接一次效率会比较低,建议使用redis连接池来替换,例如

连接池

  1. import redis
  2. # 创建redis连接池(默认连接池最大连接数 2**31=2147483648)
  3. pool = redis.ConnectionPool(host='ip地址', port=6379, password='密码', encoding='utf-8', max_connections=1000)
  4. # 去连接池中获取一个连接
  5. conn = redis.Redis(connection_pool=pool)
  6. # 设置键值:15131255089="9999" 且超时时间为10秒(值写入到redis时会自动转字符串)
  7. conn.set('name', "小小", ex=10)
  8. # 根据键获取值:如果存在获取值(获取到的是字节类型);不存在则返回None
  9. value = conn.get('name')
  10. print(value)

 

django-redis

安装

pip3 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": "密码",
        }
    }
}

视图中操作连接

from django_redis import get_redis_connection
conn
= get_redis_connection() conn.set(phone, random_code, ex=30)

 

posted @ 2020-02-24 22:27  流年中渲染了微笑  阅读(2189)  评论(0编辑  收藏  举报