Table of Contents
1. Update strategy
2. Read-write cache
1. Synchronous direct write strategy
2. Asynchronous write delay strategy
3. Double check locking strategy
4. Update strategy for database and cache consistency
1. Update the database first, then update Redis
2. Update the cache first, then update the database
3. Delete the cache first, and then update the database.
Delayed double deletion
4. Update the database first, then delete the cache
5. Summary
5. Working principle of MySQL master-slave replication
Home Database Mysql Tutorial What is the update strategy for MySQL database and Redis cache consistency?

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

May 27, 2023 pm 03:11 PM
mysql redis

    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;
        }
    }
    Copy after login

    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);
    }
    Copy after login

    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 of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    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

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

    Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

    Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

    Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

    MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

    MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

    MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 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.

    How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

    How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

    Laravel8 optimization points Laravel8 optimization points Apr 18, 2025 pm 12:24 PM

    Laravel 8 provides the following options for performance optimization: Cache configuration: Use Redis to cache drivers, cache facades, cache views, and page snippets. Database optimization: establish indexing, use query scope, and use Eloquent relationships. JavaScript and CSS optimization: Use version control, merge and shrink assets, use CDN. Code optimization: Use Composer installation package, use Laravel helper functions, and follow PSR standards. Monitoring and analysis: Use Laravel Scout, use Telescope, monitor application metrics.

    Redis's Role: Exploring the Data Storage and Management Capabilities Redis's Role: Exploring the Data Storage and Management Capabilities Apr 22, 2025 am 12:10 AM

    Redis plays a key role in data storage and management, and has become the core of modern applications through its multiple data structures and persistence mechanisms. 1) Redis supports data structures such as strings, lists, collections, ordered collections and hash tables, and is suitable for cache and complex business logic. 2) Through two persistence methods, RDB and AOF, Redis ensures reliable storage and rapid recovery of data.

    How to safely store JavaScript objects containing functions and regular expressions to a database and restore? How to safely store JavaScript objects containing functions and regular expressions to a database and restore? Apr 19, 2025 pm 11:09 PM

    Safely handle functions and regular expressions in JSON In front-end development, JavaScript is often required...

    See all articles