search
HomeDatabaseRedisHow Django uses Redis for caching

How Django uses Redis for caching

May 27, 2023 am 10:52 AM
redisdjango

    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!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    Redis: Beyond SQL - The NoSQL PerspectiveRedis: Beyond SQL - The NoSQL PerspectiveMay 08, 2025 am 12:25 AM

    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: A Comparison to Traditional Database ServersRedis: A Comparison to Traditional Database ServersMay 07, 2025 am 12:09 AM

    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.

    Redis: Introduction to a Powerful In-Memory Data StoreRedis: Introduction to a Powerful In-Memory Data StoreMay 06, 2025 am 12:08 AM

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

    Is Redis Primarily a Database?Is Redis Primarily a Database?May 05, 2025 am 12:07 AM

    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.

    Redis: Database, Server, or Something Else?Redis: Database, Server, or Something Else?May 04, 2025 am 12:08 AM

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

    Redis: Unveiling Its Purpose and Key ApplicationsRedis: Unveiling Its Purpose and Key ApplicationsMay 03, 2025 am 12:11 AM

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

    Redis: A Guide to Key-Value Data StoresRedis: A Guide to Key-Value Data StoresMay 02, 2025 am 12:10 AM

    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: Caching, Session Management, and MoreRedis: Caching, Session Management, and MoreMay 01, 2025 am 12:03 AM

    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.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

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

    Hot Tools

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools