让redis集成到django的库--django-redis

安装

pip install django-redis

配置

作为 cache backend 使用配置

为了使用 django-redis , 你应该将你的 django cache setting 改成这样:

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

为了更好的互操作性并使连接字符串更加 “标准”, 从 3.8.0 开始 django-redis 使用 redis-py native url notation 作为连接字符串.

URL 格式举例

redis://[:password]@localhost:6379/0
rediss://[:password]@localhost:6379/0
unix://[:password]@/path/to/socket.sock?db=0

支持三种 URL scheme :

  • redis://: 普通的 TCP 套接字连接
  • rediss://: SSL 包裹的 TCP 套接字连接
  • unix://: Unix 域套接字连接

指定数据库数字的方法:

  • db 查询参数, 例如: redis://localhost?db=0
  • 如果使用 redis:// scheme, 可以直接将数字写在路径中, 例如: redis://localhost/0

在某些环境下连接密码放在 url 是不安全的, 这时你可以忽略密码或者使用方便的 OPTIONS 设置:

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "PASSWORD": "mysecret"
        }
    }
}

注意, 如果你已经在 uri 中设置了密码,那么这样配置就不会覆盖 uri 中的密码, 此设置将被忽略.

套接字超时

套接字超时设置使用 SOCKET_TIMEOUT 和 SOCKET_CONNECT_TIMEOUT 参数:

CACHES = {
    "default": {
        # ...
        "OPTIONS": {
            "SOCKET_CONNECT_TIMEOUT": 5,  # in seconds
            "SOCKET_TIMEOUT": 5,  # in seconds
        }
    }
}

SOCKET_CONNECT_TIMEOUT : socket 建立连接超时设置

SOCKET_TIMEOUT : 连接建立后的读写操作超时设置

压缩支持

django-redis 支持压缩, 但默认是关闭的. 你可以激活它:

CACHES = {
    "default": {
        # ...
        "OPTIONS": {
            "COMPRESSOR": "django_redis.compressors.zlib.ZlibCompressor",
        }
    }
}

使用 lzma 压缩的例子:

import lzma

CACHES = {
    "default": {
        # ...
        "OPTIONS": {
            "COMPRESSOR": "django_redis.compressors.lzma.LzmaCompressor",
        }
    }
}

memcached 异常行为

在某些情况下, redis 只作为缓存使用, 当它关闭时如果你不希望触发异常. 这是 memcached backend 的默认行为, 你可以使用 django-redis 模拟这种情况.

为了设置这种类似memcached 的行为 ( 忽略连接异常 ), 使用 IGNORE_EXCEPTIONS 参数:

CACHES = {
    "default": {
        # ...
        "OPTIONS": {
            "IGNORE_EXCEPTIONS": True,
        }
    }
}

当然,你也可以给所有缓存配置相同的忽略行为:

DJANGO_REDIS_IGNORE_EXCEPTIONS = True

连接池

django-redis 使用 redis-py 的连接池接口, 并提供了简单的配置方式. 除此之外, 你可以为 backend 定制化连接池的产生.

redis-py 默认不会关闭连接, 尽可能重用连接

配置默认连接池

配置默认连接池很简单, 你只需要在 CACHES 中使用 CONNECTION_POOL_KWARGS 设置连接池的最大连接数量即可:

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        ...
        "OPTIONS": {
            "CONNECTION_POOL_KWARGS": {"max_connections": 100}
        }
    }
}

你可以得知连接池已经打开多少连接:

from django.core.cache import get_cache
from django_redis import get_redis_connection

r = get_redis_connection("default")  # Use the name you have defined for Redis in settings.CACHES
connection_pool = r.connection_pool
print("Created connections so far: %d" % connection_pool._created_connections)

使用你自己的连接池子类

如果需要使用自己的连接池子类.

django-redis 提供了 CONNECTION_POOL_CLASS 来配置连接池子类

myproj/mypool.py

from redis.connection import ConnectionPool

class MyOwnPool(ConnectionPool):
    # Just doing nothing, only for example purpose
    pass

setting.py

# Omitting all backend declaration boilerplate code.

"OPTIONS": {
    "CONNECTION_POOL_CLASS": "myproj.mypool.MyOwnPool",
}

集群配置

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": [
            "redis://127.0.0.1:7000/0",
            "redis://127.0.0.1:7001/0",
            "redis://127.0.0.1:7002/0",
        ],
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "REDIS_CLIENT_KWARGS": {"decode_responses": True},
        },
    }
}

分片配置

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": [
            "redis://127.0.0.1:6379/1",
            "redis://127.0.0.1:6379/2",
        ],
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.ShardClient",
            "REDIS_CLIENT_KWARGS": {"decode_responses": True},
        }
    }
}

操作

永不超时设置

django-redis 支持永不超时设置. 其表现和 django backend 指定的相同:

  • timeout=0 立即过期
  • timeout=None 永不超时
from django.core.cache import cache

cache.set("key", "value", timeout=None)

通过值 (value) 获取 ttl (time to live)

在 redis 中, 你可以获取任何 key 的 ttl, django-redis 也支持获取 ttl 的函数:

它返回:

  • 0 key 不存在 (或已过期).
  • None key 存在但没有设置过期.
  • ttl 任何有超时设置的 key 的超时值.

例如

>>> from django.core.cache import cache
>>> cache.set("foo", "value", timeout=25)
>>> cache.ttl("foo")
25
>>> cache.ttl("not-existent")
0

expire & persist

除了简单的 ttl 查询, 你可以使用 persist 或者 expire 方法让一个值永久存在或者指定一个新的过期时间:

使用 persist 的例子:

>>> cache.set("foo", "bar", timeout=22)
>>> cache.ttl("foo")
22
>>> cache.persist("foo")
>>> cache.ttl("foo")
None

使用 expire 的例子:

>>> cache.set("foo", "bar", timeout=22)
>>> cache.expire("foo", timeout=5)
>>> cache.ttl("foo")
5

locks

django-redis 支持 redis 分布式锁. 锁的线程接口是相同的, 因此你可以使用它作为替代.

使用 python 上下文管理器分配锁的例子:

with cache.lock("somekey"):
    do_some_thing()

扫描 & 删除键 (keys)

django-redis 支持使用全局通配符的方式来检索或者删除键.

使用通配符搜索

>>> from django.core.cache import cache
>>> cache.keys("foo_*")
["foo_1", "foo_2"]

这个简单的写法将返回所有匹配的值, 但在拥有很大数据量的数据库中这样做并不合适.

在 redis 的 server side cursors 2.8 版及以上, 你可以使用 iter_keys 取代 keys 方法, iter_keys 将返回匹配值的迭代器, 你可以使用迭代器高效的进行遍历.

使用 游标 搜索

>>> from django.core.cache import cache
>>> cache.iter_keys("foo_*")
<generator object algo at 0x7ffa9c2713a8>
>>> next(cache.iter_keys("foo_*"))
"foo_1"

使用 delete_pattern

如果要删除键, 使用 delete_pattern 方法, 它和 keys 方法一样也支持全局通配符, 此函数将会返回删掉的键的数量

>>> from django.core.cache import cache
>>> cache.delete_pattern("foo_*")

Redis 本地命令

django-redis 有限制的支持一些 Redis 原子操作, 例如 SETNX 和 INCR 命令.

你可以在 set() 方法中加上 nx 参数使用来使用 SETNX 命令

>>> from django.core.cache import cache
>>> cache.set("key", "value1", nx=True)
True
>>> cache.set("key", "value2", nx=True)
False
>>> cache.get("key")
"value1"

当值 (value) 有合适的键 (key) 时, incr 和 decr 也可以使用 Redis 原子操作

posted @ 2024-05-20 17:35  厚礼蝎  阅读(40)  评论(0编辑  收藏  举报