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

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Repo: How To Revive Teammates
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Hello Kitty Island Adventure: How To Get Giant Seeds
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

    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)

    How to optimize MySQL query performance in PHP? How to optimize MySQL query performance in PHP? Jun 03, 2024 pm 08:11 PM

    MySQL query performance can be optimized by building indexes that reduce lookup time from linear complexity to logarithmic complexity. Use PreparedStatements to prevent SQL injection and improve query performance. Limit query results and reduce the amount of data processed by the server. Optimize join queries, including using appropriate join types, creating indexes, and considering using subqueries. Analyze queries to identify bottlenecks; use caching to reduce database load; optimize PHP code to minimize overhead.

    How to use MySQL backup and restore in PHP? How to use MySQL backup and restore in PHP? Jun 03, 2024 pm 12:19 PM

    Backing up and restoring a MySQL database in PHP can be achieved by following these steps: Back up the database: Use the mysqldump command to dump the database into a SQL file. Restore database: Use the mysql command to restore the database from SQL files.

    How to insert data into a MySQL table using PHP? How to insert data into a MySQL table using PHP? Jun 02, 2024 pm 02:26 PM

    How to insert data into MySQL table? Connect to the database: Use mysqli to establish a connection to the database. Prepare the SQL query: Write an INSERT statement to specify the columns and values ​​to be inserted. Execute query: Use the query() method to execute the insertion query. If successful, a confirmation message will be output.

    How to fix mysql_native_password not loaded errors on MySQL 8.4 How to fix mysql_native_password not loaded errors on MySQL 8.4 Dec 09, 2024 am 11:42 AM

    One of the major changes introduced in MySQL 8.4 (the latest LTS release as of 2024) is that the "MySQL Native Password" plugin is no longer enabled by default. Further, MySQL 9.0 removes this plugin completely. This change affects PHP and other app

    How to use MySQL stored procedures in PHP? How to use MySQL stored procedures in PHP? Jun 02, 2024 pm 02:13 PM

    To use MySQL stored procedures in PHP: Use PDO or the MySQLi extension to connect to a MySQL database. Prepare the statement to call the stored procedure. Execute the stored procedure. Process the result set (if the stored procedure returns results). Close the database connection.

    Caching mechanism and application practice in PHP development Caching mechanism and application practice in PHP development May 09, 2024 pm 01:30 PM

    In PHP development, the caching mechanism improves performance by temporarily storing frequently accessed data in memory or disk, thereby reducing the number of database accesses. Cache types mainly include memory, file and database cache. Caching can be implemented in PHP using built-in functions or third-party libraries, such as cache_get() and Memcache. Common practical applications include caching database query results to optimize query performance and caching page output to speed up rendering. The caching mechanism effectively improves website response speed, enhances user experience and reduces server load.

    How to create a MySQL table using PHP? How to create a MySQL table using PHP? Jun 04, 2024 pm 01:57 PM

    Creating a MySQL table using PHP requires the following steps: Connect to the database. Create the database if it does not exist. Select a database. Create table. Execute the query. Close the connection.

    The difference between oracle database and mysql The difference between oracle database and mysql May 10, 2024 am 01:54 AM

    Oracle database and MySQL are both databases based on the relational model, but Oracle is superior in terms of compatibility, scalability, data types and security; while MySQL focuses on speed and flexibility and is more suitable for small to medium-sized data sets. . ① Oracle provides a wide range of data types, ② provides advanced security features, ③ is suitable for enterprise-level applications; ① MySQL supports NoSQL data types, ② has fewer security measures, and ③ is suitable for small to medium-sized applications.

    See all articles