redis在Django中怎么使用
在utils/redis_pool.py文件 创建
import redis
POOL = redis.ConnectionPool(max_connections=10, decode_responses=True)
from utils.redis_pool import POOL
import redis
class pooltestView(APIView):
def get(self, request, *args, **kwargs):
conn = redis.Redis(connection_pool=POOL)
conn.incrby('age')
res = conn.get('age')
return APIResponse(msg=f'接口被访问了多少次!!')

方式一:通用方式
import redis
POOL = redis.ConnectionPool(max_connections=10, decode_responses=True)
from utils.pool import POOL
import redis
class RedisView(ViewSet):
def list(self, request):
conn = redis.Redis(connection_pool=POOL)
conn.incrby('count')
count = conn.get('count')
return APIResponse(msg='您是第%s个访问的' % count)
方式二:django-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}
}
}
}
from django_redis import get_redis_connection
class pooltestView(APIView):
def get(self, request, *args, **kwargs):
conn = get_redis_connection()
conn.incrby('age')
res = conn.get('age')
return APIResponse(msg=f'接口被访问了多少次!!')
方式三:django的缓存
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}
}
}
}
cache.set 和cache.get 操作redis,用它错缓存 ---》非常简单
-优势:redis 分数据类型, 只能设置5种数据类型
-django的缓存来讲 ,不限制类型,可以放python的任意类型
-django的缓存来讲,cache.set('redis的key','不区分类型:放python的任意类型')
-cache.get('userinfo')
-django cache 底层是基于: 把你存储的类型---》使用pickle序列化--》bytes格式---》当redis的字符串形式存到redis中
-以后咱们做redis的操作,可以直接使用django的缓存, 不需要考虑类型