Django利用redis缓存数据

行云流水
2023-04-24 / 0 评论 / 383 阅读 / 正在检测是否收录...

前言

项目开发过程中,接口请求数据有一些临时数据。写入数据库,怕后期用户多了,影响性能。所以打算利用redis缓存临时数据,记录设置过程。

安装模块

pip install -i https://mirrors.aliyun.com/pypi/simple/ django-redis==5.2.0

启动redis

docker

 redis:
    image: redis:latest
    ports:
      - "6379:6379"
    volumes:
      - /etc/localtime:/etc/localtime:ro
      - ./services/redis/redis.conf:/etc/redis/redis.conf
      - ./data/redis:/data
    environment:
      TIME_ZONE: Asia/Shanghai
    command: ["redis-server", "/etc/redis/redis.conf"]
    restart: always
    sysctls:
      - net.core.somaxconn=65535
    networks:
      - lnet

redis.conf

bind 0.0.0.0
port 6379
tcp-backlog  1024
timeout 0
tcp-keepalive 0

#设置为内存大小
maxmemory 128M

#当达到内存最大值,删除所有key中访问频率最少的key
maxmemory-policy allkeys-lfu

databases 2
requirepass redis@xxxx

#禁用惰性删除
lazyfree-lazy-eviction no

#定期删除策略
#单位为秒
hz 600

使用

from django.core.cache import cache

# 设置10分钟缓存
cache.set(order_uid, json.dumps(notify_dict), 10*60)

##是否存在缓存
if cache.has_key(req_json['orderno']):
    noti_dict = json.loads(cache.get(req_json['orderno']))
    noti_url = noti_dict.pop('req_api')

评论 (0)

取消
只有登录/注册用户才可评论