当前位置:网站首页>Redis' transaction mechanism
Redis' transaction mechanism
2022-07-05 15:04:00 【Back end regular developers】
List of articles
When it comes to business , I believe we are all familiar , The transaction ACID Four characteristics , It is also often asked during the interview , But in general , We may think of transactions in traditional relational databases , Actually ,Redis It also provides a transaction mechanism , This blog will explain Redis Transaction mechanism of .
One 、 Transaction presentation
Redis Transaction provides a way to package multiple command requests , And then one time 、 A mechanism for executing multiple commands sequentially .
During the execution of the transaction , The server does not interrupt transactions to execute command requests from other clients , It will complete the execution of all commands in the transaction , Then you can process the command requests of other clients .
The figure below shows a Redis The execution of a transaction :

It can be seen that , Business to MULTI Command start , Then put multiple commands into the transaction , Finally by EXEC The command submits this transaction to the server for execution .
Two 、 Transaction implementation principle
A transaction will experience the following from the beginning to the end 3 Stages :
- The transaction start
- Order to join the team
- Transaction execution
2.1 The transaction start
MULTI The execution of the command marks the beginning of the transaction .

After executing the order , Client state flags Property will open REDIS_MULTI identification , Indicates that the client switches from non transactional state to transactional state .
2.2 Order to join the team
When a client is in a non transactional state , The command sent by this client will be executed by the server immediately :

When a client is in a transactional state , The command sent by this client , Whether the server will execute immediately , Divided into the following 2 In this case :
- If the command sent by the client is
MULTI、EXEC、WATCH、DISCARDOne of the four commands 1 individual , The server will execute this command immediately . - If the command sent by the client is the above 4 Commands other than commands , The server will not execute this command immediately , Instead, put it in the transaction queue , And back to the client
QUEUEDreply .
The above process can be represented by the following flow chart :

First of all DISCARD command , This command is used to cancel the transaction , Give up executing all commands within the transaction block , As shown below :

Then lift the transaction queue , Every Redis Each client has its own transaction state , The transaction state is stored in the client state mstates In the attribute :
The transaction state contains 1 Transaction queues and 1 Number of queued orders , As shown below :

The transaction queue is a multiCmd An array of types , Every... In the array multiCmd Structure stores information about a queued command , such as :
- Pointer to the command implementation function , Such as GET command 、SET command
- Arguments to the command
- Number of parameters
Transaction queue with fifo (FIFO) The way to keep the order to join the team .
2.3 Transaction execution
When a client in a transactional state executes EXEC On command , The server will traverse the transaction queue of this client , Execute all commands saved in the queue ( In first in first out order ), Then the result of executing the command is returned to the client at one time .
3、 ... and 、WATCH Command implementation principle
WATCH The command is used to monitor any number of database keys , And in EXEC When the order is executed , Detect whether the monitored key is modified , If it's modified , The server will refuse to execute the transaction , And return an empty reply to the client .
For better understanding , Let's make a demonstration , First , We open the client 1, perform WATCH Command monitor key “name”, And then start a transaction :

here , Don't execute EXEC command , Open client 2, Execute the following command to modify “name” Value of key :

then , On the client side 1 perform EXEC On command , An empty reply will be returned , because “name” The value of the key is on the client 2 Has been modified :

that ,WATCH What is the principle of command implementation ? We start from 3 Analyze... In every way :
- Use
WATCHCommand monitor database key - Trigger of monitoring mechanism
- Determine whether the transaction is safe
3.1 Use WATCH Command monitor database key
Every Redis Databases are kept 1 individual watched_keys Dictionaries , The key of this dictionary is a certain quilt WATCH Database key for command monitoring , The value of a dictionary is a linked list , All clients monitoring the corresponding database key are recorded in the linked list .

for instance , If the client 1 Monitoring key “name”, client 2 Monitoring key “age”, that watched_keys The data stored in the dictionary is roughly as follows :
If the client at this time 3 Executed the following WATCH command :
that watched_keys The data stored in the dictionary becomes :

3.2 Trigger of monitoring mechanism
So here comes the question , since watched_keys The dictionary is stored by WATCH Command monitor key , So how is the monitoring mechanism triggered ?
The answer is all commands to modify the database , such as SET、LPUSH、SADD etc. , After the implementation, they will be right watched_keys Dictionary check , If a client is monitoring the key just modified by the command , Then all clients that monitor this key REDIS_DIRTY_CAS The logo will be opened , Indicates that the transaction security of the client has been compromised .
Pictured above is an example , If key “name” The value of is modified , So the client 1、 client 3 Of REDIS_DIRTY_CAS The logo will be opened .
3.3 Determine whether the transaction is safe
The last critical step is , When the server receives a client sent EXEC On command , The server will depend on whether the client is open REDIS_DIRTY_CAS Flag to decide whether to execute the transaction , The flow chart of judgment is as follows :

Four 、 Example of transaction execution failure
First of all, let's see No 1 An example , This transaction was rejected by the server due to an error in the command queue , All commands in the transaction will not be executed :

Look at the first 2 An example , A nonexistent command appeared when the transaction was queued , The server will refuse to execute this transaction :
Look at the first 3 An example ,RPUSH An error is reported during the execution of the order , But the subsequent orders continue to be executed , And the previously executed commands have not been affected :
This example also shows Redis Transaction does not support rollback mechanism .
5、 ... and 、 summary
Redis Transaction provides a way to package multiple commands , And then one time 、 A mechanism for orderly execution ,
Its principle is that multiple commands will be queued into the transaction queue , Then press first in, first out (FIFO) Sequential execution ,
And the transaction will not be interrupted during execution , When all the commands in the transaction queue have been executed , It's the end of the business .
from :https://www.cnblogs.com/zwwhnly/p/13395106.html
边栏推荐
- GPS原始坐标转百度地图坐标(纯C代码)
- Does maxcompute have SQL that can query the current storage capacity (KB) of the table?
- Coding devsecops helps financial enterprises run out of digital acceleration
- 12 MySQL interview questions that you must chew through to enter Alibaba
- Super wow fast row, you are worth learning!
- 可视化任务编排&拖拉拽 | Scaleph 基于 Apache SeaTunnel的数据集成
- Isn't it right to put money into the external market? How can we ensure safety?
- sql server char nchar varchar和nvarchar的区别
- 黑马程序员-软件测试-10阶段2-linux和数据库-44-57为什么学习数据库,数据库分类关系型数据库的说明Navicat操作数据的说明,Navicat操作数据库连接说明,Navicat的基本使用,
- ICML 2022 | 探索语言模型的最佳架构和训练方法
猜你喜欢

1330:【例8.3】最少步数

你童年的快乐,都是被它承包了

想进阿里必须啃透的12道MySQL面试题

MySQL之CRUD

Interview shock 62: what are the precautions for group by?

Talk about your understanding of microservices (PHP interview theory question)

Change multiple file names with one click

FR练习题目---简单题

Photoshop插件-动作相关概念-ActionList-ActionDescriptor-ActionList-动作执行加载调用删除-PS插件开发

How to paste the contents copied by the computer into mobaxterm? How to copy and paste
随机推荐
机器学习笔记 - 灰狼优化
CPU design practice - Chapter 4 practical task 2 using blocking technology to solve conflicts caused by related problems
Install and configure Jenkins
危机重重下的企业发展,数字化转型到底是不是企业未来救星
PyTorch二分类时BCELoss,CrossEntropyLoss,Sigmoid等的选择和使用
Live broadcast preview | how to implement Devops with automatic tools (welfare at the end of the article)
R 熵权法计算权重及综合得分
Type declaration of all DOM elements in TS
There is a powerful and good-looking language bird editor, which is better than typora and developed by Alibaba
What are the domestic formal futures company platforms in 2022? How about founder metaphase? Is it safe and reliable?
Run faster with go: use golang to serve machine learning
P6183 [USACO10MAR] The Rock Game S
Stop B makes short videos, learns Tiktok to die, learns YouTube to live?
浅谈Dataset和Dataloader在加载数据时如何调用到__getitem__()函数
30岁汇源,要换新主人了
市值蒸发超百亿美元,“全球IoT云平台第一股”赴港求生
No one consults when doing research and does not communicate with students. UNC assistant professor has a two-year history of teaching struggle
长列表优化虚拟滚动
想问下大家伙,有无是从腾讯云MYSQL同步到其他地方的呀?腾讯云MySQL存到COS上的binlog
我想咨询一下,mysql一个事务对于多张表的更新,怎么保证数据一致性的?