django中使用redis多种方法

django中使用redis

方式一,自定义包方案

通用的,不针对某个框架,所有框架都能用

写一个pool.py,设置链接池

import redis

# 链接池
POOL = redis.ConnectionPool(max_connections=100)
"无论怎么导都是单例"

在需要使用的地方导入使用(接口)

from django.http import JsonResponse
from utils.pool import POOL
import redis
def test_redis(request):
    # 指定链接池
    conn=redis.Redis(connection_pool=POOL)
    # 每次访问自增1
    conn.incr('count')
    # 拿出来看看编号
    res=conn.get('count')
    return JsonResponse(f'这个接口被访问的访问次数:{res}',safe=False,json_dumps_params={'ensure_ascii':False})

记得设置路由

方式二,django方案

1,diango的缓存使用redis

settings中配置

这个也需要下载 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.http import JsonResponse
from django.core.cache import cache
# django使用redis作为缓存
def test_redis(request):
    # 没办法使用redis方法,只能手动取出来加 需要提前先放进去一个因为缓存里现在没有count  cache.set('count',1)
    res=cache.get('count')
    cache.set('count',res+1)
    return JsonResponse(f'这个接口被访问的访问次数:{res}',safe=False,json_dumps_params={'ensure_ascii':False})
"这里拿的不是redis本身的count,还是django把redis作为缓存存在了redis里别的地方的:conut"

2.第三方 django-redis提供

 也需要配置文件哦
from django.http import JsonResponse
from django_redis import get_redis_connection
# django-redis
def test_redis(request):
    # 从我们配置文件中 配置的的链接池里拿出一个链接
    conn=get_redis_connection()
    # 拿的是redis的count
    res=conn.get('count')
    return JsonResponse(f'这个接口被访问的访问次数:{res}',safe=False,json_dumps_params={'ensure_ascii':False})
posted @ 2023-03-08 17:07  李阿鸡  阅读(758)  评论(0编辑  收藏  举报
Title