[django] How to use django-redis

1. Description

As a cache database, redis is very useful in all aspects. Python supports the operation of redis. If you use Django, there is a redis library specially designed for Django, namely django-redis

2. Install

pip install django-redis

3. Configuration

3.1 configure redis

Open the Django configuration file, such as setting.py, and set the CACHES item in it

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

Multiple redis connection information can be configured in a CACHES, each with its own alias (alias), the above "default" is the alias, and then you can connect to different redis databases through different aliases

LOCATION is the connection information, including the ip port user password, etc. If the user password is not required, it can be omitted. django-redis supports three connection protocols, as follows

protocol illustrate example
redis:// Ordinary TCP socket connection redis://[[username]:[password]]@localhost:6379/0
rediss TCP socket connection in SSL mode rediss://[[username]:[password]]@localhost:6379/0
rediss:// Unix domain socket connection unix://[[username]:[password]]@/path/to/socket.sock?db=0
3.2 Use redis to store sessions

The default session of Django is stored in the sql database, but we all know that ordinary data will be stored on the hard disk, and the speed is not so fast. If you want to change it to be stored in redis, you only need to configure it in the configuration file.

SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"
3.3 Redis connection timeout setting

The number of seconds of connection timeout can be specified in the configuration item, SOCKET_CONNECT_TIMEOUT means the timeout time of connecting to redis, SOCKET_TIMEOUT means the timeout time of using redis for read and write operations

CACHES = {
    
    
    "default": {
    
    
        # ...
        "OPTIONS": {
    
    
            "SOCKET_CONNECT_TIMEOUT": 5,  # 连接redis超时时间,单位为秒
            "SOCKET_TIMEOUT": 5,  # redis读写操作超时时间,单位为秒
        }
    }
}

4. Use redis

4.1 Use the default redis

If you want to use the default redis, that is, redis with the alias "default" set in the configuration file, you can refer to the cache in django.core.cache

from django.core.cache import cache

cache.set("name", "冰冷的希望", timeout=None)
print(cache.get("name"))
4.2 Use specified redis (native redis)

When you write multiple redis connections in the configuration file, you can specify which redis to use through the alias

from django_redis import get_redis_connection

redis_conn = get_redis_connection("chain_info")
redis_conn.set("name", "icy_hope")
print(redis_conn.get("name"))

It should be noted that the client obtained through get_redis_connection() is a native Redis client. Although it basically supports all native redis commands, the data it returns is byte type, and you need to decode it yourself

5. Connection pool

The advantage of using a connection pool is that it does not need to manage connection objects. It will automatically create some connection objects and reuse them as much as possible, so the performance will be better.

5.1 Configure connection pool

To use the connection pool, first write the maximum number of connections in the connection pool in the Django configuration file

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

We can determine which redis to use through the connection alias, and then execute the command normally. We don't care which connection instances it creates, but you can check how many connection instances are currently created through the _created_connections attribute of connection_pool

from django_redis import get_redis_connection

redis_conn = get_redis_connection("default")
redis_conn.set("name", "冰冷的希望")
print(redis_conn.get("name"))

# 查看目前已创建的连接数量
connection_pool = redis_conn.connection_pool
print(connection_pool._created_connections)
5.3 Custom connection pool

The default connection class of Django-redis is DefaultClient. If you have higher customization requirements, you can create a new class of your own and inherit ConnectionPool

from redis.connection import ConnectionPool

class MyPool(ConnectionPool):
    pass

After you have this class, you need to specify it in the Django configuration file

"OPTIONS": {
    
    
    "CONNECTION_POOL_CLASS": "XXX.XXX.MyPool",
}

Guess you like

Origin blog.csdn.net/qq_39147299/article/details/127655010
Recommended