3

【笔记】Django项目中连接Redis

 1 year ago
source link: https://loli.fj.cn/2023/01/12/Django%E9%A1%B9%E7%9B%AE%E4%B8%AD%E8%BF%9E%E6%8E%A5Redis/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Django项目中连接Redis学习笔记

pip3 install redis
pip3 install django-redis

修改全局配置

  • 在全局配置中的DATABASES配置后添加CACHES配置

CLIENT_CLASS:指定客户端
CONNECTION_POOL_KWARGS:指定连接池配置

max_connections:指定最大连接数

PASSWORD:指定密码,如果没有就不指定

<project_name>/<project_name>/settings.py

CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://127.0.0.1:6379',
'OPTRONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
'CONNECTION_POOL_KWARGS': {'max_connections': 200},
#'PASSWORD': ''
}
}
}

Redis装饰器作为Mysql的缓存

  • 在从Mysql中查询数据时,先从Redis中查询
    • 如果能从Redis查询到数据,则直接从Redis中获取
    • 如果不能从Redis查询到数据,则从Mysql中查询数据,并存入Redis
import json
from functools import wraps
from django_redis import get_redis_connection
from django.db import models

定义一个缓存修饰器
_cache = get_redis_connection('default')
def cache(func):
@wraps(func)
def wrapper(obj, *args):
key = args[0]
value = _cache.get(key)
if value:
return json.loads(value)
result = func(obj, *args)
_cache.set(key, json.dumps(result))
return result
return wrapper

class User(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=5)

利用缓存修饰器定义一个类方法`get()`,当需要从缓存中获取数据时,直接调用`get()`方法即可
@classmethod
@cache
def get(cls, id):
从Mysql中查询数据,并保存到Redis
result = cls.objects.get(id=id)
return {
'id': result.id,
'name': result.name
如果有时间类型的数据,需要转换成字符串
#'time': str(result.time)
}
from django_redis import get_redis_connection
cache = get_redis_connection('default')

添加或修改

不指定过期时间

cache.set('<key>', '<value>')

指定过期时间

<num>:指定过期时间,单位:秒

cache.set('<key>', '<value>', <num>)

哔哩哔哩——图灵学院教程


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK