search
HomeDatabaseMysql TutorialWhat is the update strategy for MySQL database and Redis cache consistency?

    1. Update strategy

    1. If there is data in Redis, it needs to be the same as the value in the database.

    2. If there is no data in Redis, Redis must be updated synchronously with the latest value in the database.

    2. Read-write cache

    1. Synchronous direct write strategy

    Writing to the database also writes to the Redis cache synchronously. The cache is consistent with the data in the database; for read-write cache In other words, to ensure that the data in the cache and database are consistent, it is necessary to ensure a synchronous direct write strategy.

    2. Asynchronous write delay strategy

    In some business operations, after the MySQL data is updated, Redis data is allowed to be synchronized after a certain period of time, such as logistics systems.

    When an abnormal situation occurs, the failed action has to be re-patched, and it needs to be rewritten with the help of rabbitmq or kafka.

    3. Double check locking strategy

    If multiple threads query this data in the database at the same time, then we can use a mutex lock on the first request to query the data. Live it.

    Other threads will wait until they can't get the lock at this step, wait for the first thread to query the data, and then cache it.

    Later threads come in and find that there is already a cache, so they go directly to the cache.

    public String get(String key){
        // 从Redis缓存中读取
        String value = redisTemplate.get(key);
    
        if(value != null){
            return value;
        }
    
        synchronized (RedisTest.class){
            // 重新尝试从Redis缓存中读取
            value = redisTemplate.get(key);
            if(value != null){
                return value;
            }
    
            // 从MySQL数据库中查询
            value = studentDao.get(key);
            // 写入Redis缓存
            redisTemplate.setnx(key,value,time);
            return value;
        }
    }

    4. Update strategy for database and cache consistency

    1. Update the database first, then update Redis

    If you follow common sense, this should be the case, right? So, what's the problem in this case?

    What happens if an exception occurs before updating Redis after successfully updating the database?

    The database is inconsistent with the cached data in Redis.

    2. Update the cache first, then update the database

    There will be problems in multi-thread situations.

    For example

    • Thread 1 updates redis = 200;

    • Thread 2 updates redis = 100;

    • Thread 2 updates MySQL = 100;

    • Thread 1 updates MySQL = 200;

    The result is, Redis= 100, MySQL=200; I’ll wipe it!

    3. Delete the cache first, and then update the database.

    Thread 1 deleted the Redis cache data, and then updated the MySQL database;
    Before the MySQL update was completed, Thread 2 came to kill , read cached data;
    However, the MySQL database has not been updated at this time, thread 2 reads the old value in MySQL, and then thread 2 also writes the old value to Redis as a data cache;
    Thread 1After updating the MySQL data, I found that there is already data in Redis, which has been deleted before, so I will not update it;
    It’s over. .

    Delayed double deletion

    Delayed double deletion can solve the above problem, as long as the sleep time is greater than the time for thread 2 to read data and then write to the cache, that is, thread 1 The second cache clearing operation must be performed after thread 2 writes to the cache, so as to ensure that the data in the Redis cache is up to date.

    /**
     * 延时双删
     * @autor 哪吒编程
     */
    public void deleteRedisData(Student stu){
        // 删除Redis中的缓存数据
        jedis.del(stu);
    
        // 更新MySQL数据库数据
        studentDao.update(stu);
    
        // 休息两秒
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    
        // 删除Redis中的缓存数据
        jedis.del(stu);
    }

    The biggest problem with delayed double deletion is sleep. Today when efficiency is king, it is better not to use sleep.

    I think you are slow even if you don’t sleep, but you still fall asleep...

    4. Update the database first, then delete the cache

    1. Thread 1 updates the database first, and then deletes the Redis cache;

    2. Thread 2 initiates a request before thread 1 deletes the Redis cache, and obtains the undeleted Redis cache;

    3. Thread 1 only deletes the Redis cache data at this time;

    The problem still exists, and it goes back and forth endlessly.

    How to solve this situation?

    Introduce message middleware to solve the battle, and review it in detail again.

    1. Update the database;

    2. The database writes the operation information to the binlog log;

    3. Subscribe program Extract the key and data;

    4. Try to delete the cache operation and find that the deletion failed;

    5. Send these data information to the message middleware;

    6. Get the data from the message middleware and re-operate;

    5. Summary

    Nezha recommends using the Four ways, first update the database and then delete the cache.

    The shortcomings of method ① and method ② are too obvious to be considered;
    The sleep in method ③ is always a headache;
    Method ④ is a more comprehensive solution, but it increases learning Cost and maintenance cost due to the addition of message middleware.

    5. Working principle of MySQL master-slave replication

    What is the update strategy for MySQL database and Redis cache consistency?

    1. When the data on the master server changes, its changes are written into binary events. In the log file;

    2. The salve slave server will detect the binary log on the master server within a certain time interval to detect whether it has changed.

    If the master server is detected If the server's binary event log changes, an I/O Thread is started to request the master binary event log;

    3. At the same time, the master server starts a dump Thread for each I/O Thread to send data to it. Send binary event log;

    4. Slave saves the received binary event log from the server to its own local relay log file;

    5. The salve slave server will start the SQL Thread to read the binary log from the relay log and replay it locally to make its data consistent with the main server;

    6. The final I/O Thread and SQL Thread will go to sleep and wait for the next time it is awakened.

    The above is the detailed content of What is the update strategy for MySQL database and Redis cache consistency?. 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
    Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

    InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

    MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

    Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

    Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

    MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

    MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

    MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

    MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

    MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

    MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

    MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

    The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

    SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

    MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

    The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

    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

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment