1. 程式人生 > 實用技巧 >django-redis 中文文件

django-redis 中文文件

官方文件地址:https://django-redis-chs.readthedocs.io/zh_CN/latest/

1. 介紹

django-redis 基於 BSD 許可, 是一個使 Django 支援 Redis cache/session 後端的全功能元件.

1.1 為何要用 django-redis ?

因為:

  • 持續更新
  • 本地化的 redis-py URL 符號連線字串
  • 可擴充套件客戶端
  • 可擴充套件解析器
  • 可擴充套件序列器
  • 預設客戶端主/從支援
  • 完善的測試
  • 已在一些專案的生產環境中作為 cache 和 session 使用
  • 支援永不超時設定
  • 原生進入 redis 客戶端/連線池支援
  • 高可配置 ( 例如模擬快取的異常行為 )
  • 預設支援 unix 套接字
  • 支援 Python 2.7, 3.4, 3.5 以及 3.6

1.2 可用的 django-redis 版本

  • 穩定版本: 4.7.0
  • 穩定版本: 3.8.4

1.3 我該使用哪個版本

版本號像 3.6, 3.7 … 等的是主要發行版本, 會包含向後不相容的內容. 跟多資訊請在升級前閱讀升級日誌.

版本號像 3.7.0, 3.7.1… 等的是小更新或者 bug 修復版本, 一般只會包含 bug 修復, 沒有功能更新.

1.4 依賴

1.4.1 Django 版本支援

  • django-redis 3.8.x 支援 django 1.4, 1.5, 1.6, 1.7 (或許會有 1.8)
  • django-redis 4.4.x 支援 django 1.6, 1.7, 1.8, 1.9 和 1.10

1.4.2 Redis Server 支援

  • django-redis 3.x.y 支援 redis-server 2.6.x 或更高
  • django-redis 4.x.y 支援 redis-server 2.8.x 或更高

1.4.3 其他依賴

所有版本的 django-redis 基於 redis-py >= 2.10.0.

2. 使用者指南

2.1 安裝

安裝 django-redis 最簡單的方法就是用 pip :

pip install django-redis

2.2 作為 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 中設定了密碼, 此設定將被忽略.

2.3 作為 session backend 使用配置

Django 預設可以使用任何 cache backend 作為 session backend, 將 django-redis 作為 session 儲存後端不用安裝任何額外的 backend

SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"

2.4 使用 django-redis 進行測試

django-redis 支援定製基於 Redis 的客戶端 ( 參考[可擴充套件 redis 客戶端][] ) 可以用來測試, 例如: 替換預設的客戶端為 fakerdis (https://github.com/jamesls/fakeredis) 或者 mockredis (https://github.com/locationlabs/mockredis). 這樣做可以不用依賴真的 redis server 做整合測試.

使用 fakeredis 舉例:

import fakeredis
CACHES = {
    "default": {
        "OPTIONS": {
            "REDIS_CLIENT_CLASS": "fakeredis.FakeStrictRedis",
        }
    }
}

如果在測試完畢後想清理所有資料, 在你的 TestCase 中加入如下程式碼:

def tearDown(self):
    from django_redis import get_redis_connection
    get_redis_connection("default").flushall()

3. 進階使用

3.1 Pickle 版本

django-redis 使用 pickle 序列化幾乎所有資料.

預設使用最新的 pickle. 如果你想設定其他版本, 使用 PICKLE_VERSION 引數:

CACHES = {
    "default": {
        # ...
        "OPTIONS": {
            "PICKLE_VERSION": -1  # Use the latest protocol version
        }
    }
}

3.2 套接字超時

套接字超時設定使用 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 : 連線建立後的讀寫操作超時設定

3.3 壓縮支援

django-redis 支援壓縮, 但預設是關閉的. 你可以啟用它:

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

使用 lzma 壓縮的例子:

import lzma

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

3.4 memcached 異常行為

在某些情況下, redis 只作為快取使用, 當它關閉時如果你不希望觸發異常. 這是 memcached backend 的預設行為, 你可以使用 django-redis 模擬這種情況.

為了設定這種類似memcached 的行為 ( 忽略連線異常 ), 使用 IGNORE_EXCEPTIONS 引數:

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

Also, you can apply the same settings to all configured caches, you can set the global flag in your settings:

當然,你也可以給所有快取配置相同的忽略行為:

DJANGO_REDIS_IGNORE_EXCEPTIONS = True

3.5 日誌忽略異常

當使用 IGNORE_EXCEPTIONS 或者 DJANGO_REDIS_IGNORE_EXCEPTIONS 引數忽略異常時, 你也許會用到 DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS 引數來配置日誌異常:

DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS = True

如果你想設定指定的 logger 輸出異常, 只需要設定全域性變數 DJANGO_REDIS_LOGGER 為 logger 的名稱或其路徑即可. 如果沒有 logger 被設定並且 DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS=True 時此引數將取 name :

DJANGO_REDIS_LOGGER = 'some.specified.logger'

3.6 永不超時設定

django-redis comes with infinite timeouts support out of the box. And it behaves in same way as django backend contract specifies:

django-redis 支援永不超時設定. 其表現和 django backend 指定的相同:

  • timeout=0 立即過期
  • timeout=None 永不超時
cache.set("key", "value", timeout=None)

3.7 通過值 (value) 獲取 ttl (time to live)

With redis, you can access to ttl of any stored key, for it, django-redis exposes ttl function.

It returns:

在 redis 中, 你可以獲取任何 key 的 ttl, django-redis 也支援獲取 ttl 的函式:

它返回:

  • 0 key 不存在 (或已過期).
  • None key 存在但沒有設定過期.
  • ttl 任何有超時設定的 key 的超時值.

以 keys 搜尋過期:

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

3.8 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

3.9 locks

django-redis 支援 redis 分散式鎖. 鎖的執行緒介面是相同的, 因此你可以使用它作為替代.

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

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

3.10 掃描 & 刪除鍵 (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 將返回匹配值的迭代器, 你可以使用迭代器高效的進行遍歷.

使用 server side cursors 搜尋

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

如果要刪除鍵, 使用 delete_pattern 方法, 它和 keys 方法一樣也支援全域性萬用字元, 此函式將會返回刪掉的鍵的數量

使用 delete_pattern 的例子

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

3.11 Redis 本地命令

django-redis 有限制的支援一些 Redis 原子操作, 例如 SETNXINCR 命令.

你可以在 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) 時, incrdecr 也可以使用 Redis 原子操作

3.12 原生客戶端使用

在某些情況下你的應用需要進入原生 Redis 客戶端使用一些 django cache 介面沒有暴露出來的進階特性. 為了避免儲存新的原生連線所產生的另一份設定, django-redis 提供了方法 get_redis_connection(alias) 使你獲得可重用的連線字串.

>>> from django_redis import get_redis_connection
>>> con = get_redis_connection("default")
>>> con
<redis.client.StrictRedis object at 0x2dc4510>

警告 不是所有的擴充套件客戶端都支援這個特性.

3.13 連線池

django-redis 使用 redis-py 的連線池介面, 並提供了簡單的配置方式. 除此之外, 你可以為 backend 定製化連線池的產生.

redis-py 預設不會關閉連線, 儘可能重用連線

3.13.1 配置預設連線池

配置預設連線池很簡單, 你只需要在 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)

3.13.2 使用你自己的連線池子類

有時你想使用自己的連線池子類. 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",
}

3.13.3 定製化的 connection factory

如果之前的方法都不合適, 你可以定製 django-redis 的 connection factory 過程甚至完全重寫.

django-redis 預設使用Django setting 中 DJANGO_REDIS_CONNECTION_FACTORY 引數指定的 django_redis.pool.ConnectionFactory 類產生連線.

ConnectionFactory 類的部分介面

# Note: Using Python 3 notation for code documentation ;)

class ConnectionFactory(object):
    def get_connection_pool(self, params:dict):
        # Given connection parameters in the `params` argument,
        # return new connection pool.
        # It should be overwritten if you want do something
        # before/after creating the connection pool, or return your
        # own connection pool.
        pass

    def get_connection(self, params:dict):
        # Given connection parameters in the `params` argument,
        # return a new connection.
        # It should be overwritten if you want to do something
        # before/after creating a new connection.
        # The default implementation uses `get_connection_pool`
        # to obtain a pool and create a new connection in the
        # newly obtained pool.
        pass

    def get_or_create_connection_pool(self, params:dict):
        # This is a high layer on top of `get_connection_pool` for
        # implementing a cache of created connection pools.
        # It should be overwritten if you want change the default
        # behavior.
        pass

    def make_connection_params(self, url:str) -> dict:
        # The responsibility of this method is to convert basic connection
        # parameters and other settings to fully connection pool ready
        # connection parameters.
        pass

    def connect(self, url:str):
        # This is really a public API and entry point for this
        # factory class. This encapsulates the main logic of creating
        # the previously mentioned `params` using `make_connection_params`
        # and creating a new connection using the `get_connection` method.
        pass

3.14 可擴充套件解析器

redis-py (django-redis 使用的 Redis 客戶端) 支援的純淨 Python Redis 解析器可以滿足大部分普通任務, 但如果你想要效能更好, 可以使用 hiredis

hiredis 是一個用 C 寫的 Redis 客戶端, 並且他的解析器可以用在 django-redis 中:

"OPTIONS": {
    "PARSER_CLASS": "redis.connection.HiredisParser",
}

3.15 可擴充套件客戶端

django_redis 設計的非常靈活和可配置。它提供了可擴充套件的後端,擁有易擴充套件的特性.

3.15.1 預設客戶端

我們已經說明了預設客戶端幾乎所有的特點, 但有一個例外: 預設客戶端支援主從配置.

如果需要主從設定, 你需要更改 LOCATION 引數:

"LOCATION": [
    "redis://127.0.0.1:6379/1",
    "redis://127.0.0.1:6378/1",
]

第一個欄位代表 master 伺服器, 第二個欄位代表 slave 伺服器.

警告 主從設定沒有在生產環境中經過大量測試

3.15.2 分片客戶端

此可擴充套件客戶端實現了客戶端分片, 它幾乎繼承了預設客戶端的全部功能. 如果需要使用, 請將配置改成這樣

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",
        }
    }
}

警告 分片客戶端仍處於試驗階段, 請在生產環境中謹慎使用

3.15.3 叢集客戶端

我們同時也在嘗試解決驚群問題, 更多資訊請閱讀Wikipedia

和上文講的一樣, 客戶端基本繼承了預設客戶端所有功能, 增加額外的方法以獲取/設定鍵 (keys)

設定舉例

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

一些其他的設定:

  • CACHE_HERD_TIMEOUT: 設定叢集超時 (預設值為: 60s)

3.16 可擴充套件序列器

客戶端在將資料發給伺服器之前先會序列化資料. django-redis 預設使用 Python pickle 序列化資料.

如果需要使用 json 序列化資料, 使用 JSONSerializer

設定舉例

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

使用 MsgPack http://msgpack.org/ 進行序列化 (需要 msgpack-python 庫支援)

設定舉例

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

3.17 可擴充套件 Redis 客戶端

django-redis 預設使用 redis.client.StrictClient 作為 Redis 客戶端, 你可以使用其他客戶端替代, 比如之前在講測試時我們用 fakeredis 代替真實客戶端.

使用 REDIS_CLIENT_CLASS in the CACHES 來配置你的客戶端, 使用 REDIS_CLIENT_KWARGS 提供配置客戶端的引數 (可選).

設定舉例

CACHES = {
    "default": {
        "OPTIONS": {
            "REDIS_CLIENT_CLASS": "my.module.ClientClass",
            "REDIS_CLIENT_KWARGS": {"some_setting": True},
        }
    }
}

4. 許可

Copyright (c) 2011-2015 Andrey Antukh <[email protected]>
Copyright (c) 2011 Sean Bleier

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.