django-redis 字符串操作

司徒正信
2023-12-01

安装库

django-redis==4.12.1

写入配置模块 settings.py

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/0",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
    "session": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
    "verify": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/2",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
}

views.py 调用

from django_redis import get_redis_connection

redis = get_redis_connection("verify")
# 获取
redis.get("test_")
# 写入 key 过期时间(秒) value
redis.setex("timing_test_", 60 * 30, 1)
# 删除
redis.delete("test_")
# 管道操作
pl = redis.pipeline()
pl.delete("test_")
pl.setex("timing_test", 60 * 30, 1)
pl.execute()
# incr 自增 expire 设置过期时间
pl = redis.pipeline() 
pl.incr("host_" )
pl.expire("host_" 60 * 5)
pl.execute()
 类似资料: