当前位置:网站首页>Redis cache data consistency solution analysis
Redis cache data consistency solution analysis
2022-06-26 04:05:00 【Dreamers on the road】
The article brief introduction
Redis As a non relational database , It has been applied in various high performance business scenarios .Redis It's a database based on the nature of memory , Therefore, it has very good performance in reading and writing , In actual use , Most of them are also used for business data caching .
Design to cache , We have to consider a situation , It's the consistency of the cache data . How to understand cache consistency ? Let's take a simple example , In an e-commerce system application , We store the inventory quantity of goods in the cache , At this time, we update the inventory quantity of goods in the background , How to ensure that the inventory information in the cache is updated synchronously without the problem of inventory quantity ? In the end of the article, I'll show you the code , This case is also used as a demonstration .
Cache design
Before you learn about cache design , Let's take a look at the picture below . This is also a design pattern for many caching systems .

- The client sends the request to the server . Go directly to the cache to query the data .
- If there is data in the cache , Then it is directly returned to the data in the client cache .
- If there is no data in the cache , Then query the database .
- according to MySQL Data queried in , Write to cache and return to client .
The main idea of the article
Data consistency mentioned earlier in this article , refer to MySQL How to keep up with the data in the cache . The following article also analyzes how to realize data synchronization .
Update strategy
Cache first, then database

Strategy statement
- There is an update request on the back end , Update the corresponding Redis cache . You can delete it directly in the process , Write again ; It can also be updated . It's easier to use delete .
- If the cache update fails , Return the client error message directly .
- If the cache update is successful , Then update MySQL operation .
- If MySQL Update failed , Then roll back the entire update , Including update operations in the cache .
Problem analysis
- If in the first place 1 Delete cache used in , When the first 2 Failed to update cache in , At this time, you need to manually append the cache , Otherwise Cache breakdown situation , This situation is very serious .
- In the 4 in , to update MySQL In case of failure , Will roll back the data in the cache . If it's updating MySQL In operation , New request from client , At this point, the client reads the new data , But in reality MySQL The update failed , It's impossible for users to read new data , In this way, the data will be inconsistent .
Code demonstration
// Redis Connection object
$redis = null;
// MySQL Connection object
$mysql = null;
// Client request parameters
$requestParams = [];
// Delete cache
$updateRedis = $redis->del('key');
if ($updateRedis) {
// to update MySQL
$updateMysql = $mysql->update('update xxx set a=xx where id=xxx');
if ($updateMysql) {
return ' Data update failed ';
}
// Rollback cache ( Due to cache delete failure , There is no need to roll back manually at this point . If it's an executive update Redis, You also need to roll back manually Redis)
$redis->set('key', $requestParams);
}
return ' Cache update failed ';
First database and then cache

Strategy statement
- The client initiates an update request , To update MySQL.
- MySQL After the update is successful , Then update the cache . Update cache can use delete operation directly , You can also specify updates .
- If Redis If the update fails, the client information will be returned .
Problem analysis
- This strategy can clearly see that , Updating MySQL The stage is OK .MySQL If it fails, it will return to the client directly and the update fails , There's no need to manipulate the cache .
- But when updating the cache , If the cache update fails , however MySQL The data in is updated successfully . So we are faced with this problem , Is it rolling back or not doing anything ?
- If the first 2 in , Operation cache failed , Without any processing, the cache will always be old data , Unless the cache is valid .
Code demonstration
// Redis Connection object
$redis = null;
// MySQL Connection object
$mysql = null;
// Client request parameters
$requestParams = [];
// to update MySQL
$updateMysql = $mysql->update('update xxx set a=xx where id=xxx');
if ($updateMysql) {
// Update cache
$updateRedis = $redis->set($requestParams);
if ($updateRedis) {
return ' Data updated successfully ';
}
return ' Cache update failed ';
}
return ' Data update failed ';
Multithreading synchronization

Strategy statement
- Client initiates request , At this point, two threads are created .
- One thread execution MySQL to update , A thread performs cache updates .
- If one of the two threads fails , Then roll back the entire update operation .
Problem analysis
- This strategy updates data through multiple threads , Reduce congestion problems , Speed up program processing .
- If MySQL Thread update speed failed and processing speed is slow ,Redis The update is successful and the processing speed is fast . Do a rollback at this point , In a more detailed process , New requests get new data from the cache , After the rollback, the cached data is the old data .
Code demonstration
// Redis Connection object
$redis = null;
// MySQL Connection object
$mysql = null;
// Client request parameters
$requestParams = [];
// Thread one update MySQL
$updateMysql = $mysql->update('update xxx set a=xx where id=xxx');
// Thread 2 update cache
$updateRedis = $redis->set('key', $requestParams);
if ($updateMysql && $updateRedis) {
return ' Data updated successfully ';
}
// Perform data rollback
.....
return ' Data update failed ';
Lock processing

Strategy statement
- Client initiates request , Create a lock .
- At this point, update in turn MySQL And cache data .
- No matter success or failure , Release the lock after execution .
Problem analysis
- Client initiates request , Create a lock . When creating locks , have access to set-nx The way , Avoid service hang up, cache will not automatically expire .
- to update MySQL And cache data .
- If the cache succeeds, the lock is released , If the cache fails, the lock is released .
- This method is suitable for data High consistency The situation of , For example, when the back end initiates a request , The client can't read , Release the lock until the write operation succeeds or fails .
- Use this method , The client needs to read the code to judge the lock situation . If there is a lock, it is in the waiting state . Not suitable for high concurrency business scenarios . But it ensures that the data is completely consistent .
Code demonstration
// Redis Connection object
$redis = null;
// MySQL Connection object
$mysql = null;
// Client request parameters
$requestParams = [];
/ The client initiates a lock request
// to update MySQL
$updateMysql = $mysql->update('update xxx set a=xx where id=xxx');
$updateRedis = $redis->set('key', $requestParams);
if ($updateMysql && $updateRedis) {
// Release the lock
// Return information
return ' Data updated successfully ';
}
// Release the lock
// Return information
return ' Update failed ';
Article summary
This article is an analysis of different situations . In many cases, it's just a theoretical state . Compare recommended methods , It is recommended to update first MySQL Updating cache .
Link to the original text :https://mp.weixin.qq.com/s/GdM3VrL8-pEXBLmDi_paZA
边栏推荐
- MySQL est livré avec l'outil de test de performance MySQL lap pour effectuer des tests de résistance
- 线程同步之互斥量(互斥锁)
- mysql自帶的性能測試工具mysqlslap執行壓力測試
- WPF 值转换
- win10 系统打开的软件太小,如何变大(亲测有效)
- 【Flink】Flink Sort-Shuffle写流程简析
- Verrouillage de lecture et d'écriture pour la synchronisation des fils
- mysql自带的性能测试工具mysqlslap执行压力测试
- 判断两个集合的相同值 ||不同值
- Use soapUI to access the corresponding ESB project
猜你喜欢

matplotlib折线图,文字显示,win10

An error occurred using the connection to database 'on server' 10.28.253.2‘

钉钉开放平台-小程序开发实战(钉钉小程序客户端)
![[Flink] Flink source code analysis - creation of jobgraph in batch mode](/img/8e/1190eec23169a4d2a06e1b03154d4f.jpg)
[Flink] Flink source code analysis - creation of jobgraph in batch mode

Part 4: drawing quadrilateral

线程同步之条件变量

Oracle技术分享 oracle 19.14升级19.15

开源!ViTAE模型再刷世界第一:COCO人体姿态估计新模型取得最高精度81.1AP

高性能算力中心 — RoCE — Overview

【QT】资源文件导入
随机推荐
What should I do if the 51 SCM board cannot find the device in keil
Three level menu applet
[learn FPGA programming from scratch -45]: vision chapter - integrated circuits help high-quality development in the digital era -2- market forecast
go语言泛型在IDE中语法报错
ABP framework Practice Series (III) - domain layer in depth
How do wechat applets delay? Timing? Execute a piece of code after? (kengji)
What preparation should I make before learning SCM?
[Flink] a brief analysis of the writing process of Flink sort shuffle
Nailing open platform - applet development practice (nailing applet server side)
WPF value conversion
[从零开始学习FPGA编程-45]:视野篇 - 集成电路助力数字化时代高质量发展-2-市场预测
mysql自帶的性能測試工具mysqlslap執行壓力測試
What preparations should be made to develop an app from scratch
Wechat applet is bound to a dynamic array to implement a custom radio box (after clicking the button, disable the button and enable other buttons)
Using jsup to extract images from interfaces
判断两个集合的相同值 ||不同值
How does virtual box virtual machine software accelerate the network speed in the virtual system?
解析JSON接口并批量插入到数据库中
YOLOv5改进:更换骨干网(Backbone)
Nailing open platform - applet development practice (nailing applet client)