1. Description
Redis, as a cache database, plays a great role in all aspects. Python supports operating redis. If you use Django, there is a redis library specially designed for Django, namely django- redis
2. Installation
pip install django-redis
3. Configuration
3.1 Configure redis
Open the Django configuration file, such as setting.py, and set CACHES in it Item
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 one CACHES. Each one has its own alias (alias). The "default" above is the alias. At that time, you can connect to different redis databases through different aliases
LOCATION is the connection information, including ip port user password, etc. If the user password is not required, you can omit it. django-redis supports three connection protocols, as follows
Protocol | Description | Example |
---|---|---|
Ordinary TCP suite Interface connection | redis://[[username]:[password]]@localhost:6379/0 | |
SSL mode TCP socket connection | rediss://[[username]:[password]]@localhost:6379/0 | |
Unix domain socket connection | unix://[[username]:[password]]@/path/to/socket.sock?db=0 |
SESSION_ENGINE = "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "default"3.3 redis connection timeout settingThe number of seconds for the connection timeout can be specified in the configuration item, SOCKET_CONNECT_TIMEOUT indicates the connection The timeout of redis, SOCKET_TIMEOUT represents the timeout of read and write operations using redis
CACHES = { "default": { # ... "OPTIONS": { "SOCKET_CONNECT_TIMEOUT": 5, # 连接redis超时时间,单位为秒 "SOCKET_TIMEOUT": 5, # redis读写操作超时时间,单位为秒 } } }4. Using redis4.1 Use the default redisIf you want to use the default redis , that is, the redis with the alias "default" set in the configuration file 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 the specified redis (native redis)When you Multiple redis connections are written in the configuration file. You can specify which redis to use through 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 basically all are supported Native redis command, but the data it returns is of byte type, you need to decode it yourself5. Connection poolThe advantage of using the connection pool is that you don’t need to manage the connection object, it will automatically create some connections Objects and reused as much as possible, so the performance will be relatively better5.1 Configuring the connection poolTo use the connection pool, first write the maximum connection pool size in the Django configuration file Number of connections
CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", ... "OPTIONS": { "CONNECTION_POOL_KWARGS": {"max_connections": 100} } } }5.2 Using connection poolWe can determine which redis to use through the connection alias, and then just execute the command normally. We don’t need to care about which connection instances it creates, but you can pass The _created_connections attribute of connection_pool checks how many connection instances are currently created
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 poolThe 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): passAfter you have this class, you need to specify it in the Django configuration file
"OPTIONS": { "CONNECTION_POOL_CLASS": "XXX.XXX.MyPool", }
The above is the detailed content of How to use django redis. For more information, please follow other related articles on the PHP Chinese website!

Redis goes beyond SQL databases because of its high performance and flexibility. 1) Redis achieves extremely fast read and write speed through memory storage. 2) It supports a variety of data structures, such as lists and collections, suitable for complex data processing. 3) Single-threaded model simplifies development, but high concurrency may become a bottleneck.

Redis is superior to traditional databases in high concurrency and low latency scenarios, but is not suitable for complex queries and transaction processing. 1.Redis uses memory storage, fast read and write speed, suitable for high concurrency and low latency requirements. 2. Traditional databases are based on disk, support complex queries and transaction processing, and have strong data consistency and persistence. 3. Redis is suitable as a supplement or substitute for traditional databases, but it needs to be selected according to specific business needs.

Redisisahigh-performancein-memorydatastructurestorethatexcelsinspeedandversatility.1)Itsupportsvariousdatastructureslikestrings,lists,andsets.2)Redisisanin-memorydatabasewithpersistenceoptions,ensuringfastperformanceanddatasafety.3)Itoffersatomicoper

Redis is primarily a database, but it is more than just a database. 1. As a database, Redis supports persistence and is suitable for high-performance needs. 2. As a cache, Redis improves application response speed. 3. As a message broker, Redis supports publish-subscribe mode, suitable for real-time communication.

Redisisamultifacetedtoolthatservesasadatabase,server,andmore.Itfunctionsasanin-memorydatastructurestore,supportsvariousdatastructures,andcanbeusedasacache,messagebroker,sessionstorage,andfordistributedlocking.

Redisisanopen-source,in-memorydatastructurestoreusedasadatabase,cache,andmessagebroker,excellinginspeedandversatility.Itiswidelyusedforcaching,real-timeanalytics,sessionmanagement,andleaderboardsduetoitssupportforvariousdatastructuresandfastdataacces

Redis is an open source memory data structure storage used as a database, cache and message broker, suitable for scenarios where fast response and high concurrency are required. 1.Redis uses memory to store data and provides microsecond read and write speed. 2. It supports a variety of data structures, such as strings, lists, collections, etc. 3. Redis realizes data persistence through RDB and AOF mechanisms. 4. Use single-threaded model and multiplexing technology to handle requests efficiently. 5. Performance optimization strategies include LRU algorithm and cluster mode.

Redis's functions mainly include cache, session management and other functions: 1) The cache function stores data through memory to improve reading speed, and is suitable for high-frequency access scenarios such as e-commerce websites; 2) The session management function shares session data in a distributed system and automatically cleans it through an expiration time mechanism; 3) Other functions such as publish-subscribe mode, distributed locks and counters, suitable for real-time message push and multi-threaded systems and other scenarios.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment
