1. Background and significance
Server data is updated very frequently. If data is read from the hard disk every time, server resources are wasted and response speed is slowed down. Moreover, the data update frequency is relatively high, which puts a heavy burden on the server. If you save it to the database, you need to create an additional corresponding table to store the data. The usual way to create a table in Django is to create a model. It seems simple, but it is troublesome to debug and takes a long time to develop. In order to accelerate the server, Redis is used for caching.
2. The configuration steps are as follows
1, install redis on the server side
(1)在Windows安装redis,方便测试 Redis不支持Windows!在它官网写得很清楚。但是开发环境一般是Windows系统。为了方便开发和调试,需要在Windows中安装Redis。微软自己弄了Redis的Windows版本。打开https://github.com/MSOpenTech/redis/releases下载msi安装包。该版本是64位。安装msi过程中,有个选项是否加入系统环境变量,记得勾上。一路下一步,安装。完成之后打开cmd,输入redis-server命令查看是否可以使用。不可以则重启一下即可。直接输入redis-server命令使用的配置文件是安装目录下的redis.windows.conf文件。 若提示错误 “ConnectionError: Error 10061 connecting to None:6379”,可以如下操作,打开cmd输入如下命令:`redis-cli shutdown` ,再执行redis-server即可。 (2)在ubuntu下安装,针对部署 `sudo apt-get install redis-server`
2, Redis access control
# 默认情况下,访问 Redis 服务器是不需要密码的,为了让其他服务器使用同时增加安全性我们需要设置 Redis 服务器的访问密码。设置访问密码为 yourpassword。 # 由于 redis 默认绑定本机的,所以第一步取消该设置: `sudo vim /etc/redis/redis.conf` # 用vim打开该配置文件,然后注释掉下面这行: `# bind 127.0.0.1` # 然后设置登录密码,用vim打开配置文件,配置文件较长,命令模式下输入`/requirepass foobared`快速搜索该配置项: # 编辑配置文件 `sudo vim /etc/redis/redis.conf` # 找到下面这一行并去除注释(可以搜索requirepass) # requirepass foobared 未修改之前 # 修改之后 `requirepass 123456789` # 假设123456789是我的redis密码 # 修改后重启服务器使配置生效: `sudo /etc/init.d/redis-server restart` # 此时在登录redis,权限被控制 root@VM-60-191-ubuntu:~# redis-cli 127.0.0.1:6379> keys * (error) NOAUTH Authentication required. # 用密码登录,具有权限 root@VM-60-191-ubuntu:~# redis-cli -a 123456789 127.0.0.1:6379> keys * 1) "key2" # 通过以下命令从另一台linux服务器访问redis, password替换为你的密码,host替换为要访问的服务器 `redis-cli -a password -h hostip` # 数据库的数量是可以配置的,不知道数据库就是数据库0,默认情况下是16个。修改redis.conf下的databases指令: `databases 64`
3, install django-redis and settings Add the following content to the configuration
pip install django-redis
settings.py
, replace your_host_ip
with your server address, yoursecret
with your server password
CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://your_host_ip:6379', "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "PASSWORD": "yoursecret", }, }, } REDIS_TIMEOUT=7*24*60*60 CUBES_REDIS_TIMEOUT=60*60 NEVER_REDIS_TIMEOUT=365*24*60*60 # cache中的是必须的,下面三条可有可无(超时设置啥的)
4, test whether the cache is successful
In order to test whether redis can be used normally, enter the background command mode of django:
python manage.py shell
Enter the following commands one by one to test:
from django.core.cache import cache # 引入缓存模块 cache.set('v', '555', 60*60) # 写入key为v,值为555的缓存,有效期30分钟 cache.has_key('v') # 判断key为v是否存在 cache.get('v') # 获取key为v的缓存
The above is the detailed content of How Django uses Redis for caching. For more information, please follow other related articles on the PHP Chinese website!

RedisisclassifiedasaNoSQLdatabasebecauseitusesakey-valuedatamodelinsteadofthetraditionalrelationaldatabasemodel.Itoffersspeedandflexibility,makingitidealforreal-timeapplicationsandcaching,butitmaynotbesuitableforscenariosrequiringstrictdataintegrityo

Redis improves application performance and scalability by caching data, implementing distributed locking and data persistence. 1) Cache data: Use Redis to cache frequently accessed data to improve data access speed. 2) Distributed lock: Use Redis to implement distributed locks to ensure the security of operation in a distributed environment. 3) Data persistence: Ensure data security through RDB and AOF mechanisms to prevent data loss.

Redis's data model and structure include five main types: 1. String: used to store text or binary data, and supports atomic operations. 2. List: Ordered elements collection, suitable for queues and stacks. 3. Set: Unordered unique elements set, supporting set operation. 4. Ordered Set (SortedSet): A unique set of elements with scores, suitable for rankings. 5. Hash table (Hash): a collection of key-value pairs, suitable for storing objects.

Redis's database methods include in-memory databases and key-value storage. 1) Redis stores data in memory, and reads and writes fast. 2) It uses key-value pairs to store data, supports complex data structures such as lists, collections, hash tables and ordered collections, suitable for caches and NoSQL databases.

Redis is a powerful database solution because it provides fast performance, rich data structures, high availability and scalability, persistence capabilities, and a wide range of ecosystem support. 1) Extremely fast performance: Redis's data is stored in memory and has extremely fast read and write speeds, suitable for high concurrency and low latency applications. 2) Rich data structure: supports multiple data types, such as lists, collections, etc., which are suitable for a variety of scenarios. 3) High availability and scalability: supports master-slave replication and cluster mode to achieve high availability and horizontal scalability. 4) Persistence and data security: Data persistence is achieved through RDB and AOF to ensure data integrity and reliability. 5) Wide ecosystem and community support: with a huge ecosystem and active community,

Key features of Redis include speed, flexibility and rich data structure support. 1) Speed: Redis is an in-memory database, and read and write operations are almost instantaneous, suitable for cache and session management. 2) Flexibility: Supports multiple data structures, such as strings, lists, collections, etc., which are suitable for complex data processing. 3) Data structure support: provides strings, lists, collections, hash tables, etc., which are suitable for different business needs.

The core function of Redis is a high-performance in-memory data storage and processing system. 1) High-speed data access: Redis stores data in memory and provides microsecond-level read and write speed. 2) Rich data structure: supports strings, lists, collections, etc., and adapts to a variety of application scenarios. 3) Persistence: Persist data to disk through RDB and AOF. 4) Publish subscription: Can be used in message queues or real-time communication systems.

Redis supports a variety of data structures, including: 1. String, suitable for storing single-value data; 2. List, suitable for queues and stacks; 3. Set, used for storing non-duplicate data; 4. Ordered Set, suitable for ranking lists and priority queues; 5. Hash table, suitable for storing object or structured data.


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

AI Hentai Generator
Generate AI Hentai for free.

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 CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Notepad++7.3.1
Easy-to-use and free code editor