当前位置:网站首页>Redis - 7. Transaction operation
Redis - 7. Transaction operation
2022-06-22 11:56:00 【Q.E.D.】
1、redis Transaction definition
redis A transaction is a separate isolation operation , All commands in the transaction are serialized 、 To execute in order , Transaction is in the process of execution , Will not be interrupted by command requests from other clients .
redis The main function of a transaction is to concatenate multiple commands to prevent Other orders to jump the queue .
2、Multi、Exec、discard
From input Multi Command start , All the entered commands will enter the command queue in turn , But will not execute , Until input Exec after ,redis Will execute the previous commands in sequence .
In the process of team formation, you can go through discard To give up team building .
redis Transaction sub 2 Stages : Team formation stage 、 Execution phase
- Team formation stage : Just add all commands to the command queue
- Execution phase : Execute the commands in the queue in turn , During the execution of these commands , It will not be cut in line or interrupted by the request command sent by other clients .

2.1、 Several related commands
2.1.1、multi: Mark the beginning of a transaction block
Mark the beginning of a transaction block .
Multiple commands in a transaction block are put into a queue in sequence , Finally by exec Command atomicity (atomic) Carry out smoothly .
Example
redis> MULTI # Mark transaction start
OK
redis> INCR user_id # Multiple orders in order , The return value is QUEUED, Indicates that the command is added to the queue , It hasn't been implemented yet .
QUEUED
redis> INCR user_id
QUEUED
redis> INCR user_id
QUEUED
redis> PING
QUEUED
redis> EXEC # perform
1) (integer) 1
2) (integer) 2
3) (integer) 3
4) PONG
2.1.2、exec: Execute commands within all transaction blocks
Execute commands within all transaction blocks .
If a certain ( Or something ) key Is in watch Under the watch of orders , And the transaction block has and this ( Or these ) key Related commands , that exec The order is only in this ( Or these ) key It is executed and effective without being changed by other orders , Otherwise, the transaction is interrupted (abort).
Return value :
The return value of all commands in the transaction block , In the order in which the orders are executed .
When the operation is interrupted , Returns a null value nil .
3 Example
# Example 1: The transaction was successfully executed
redis> MULTI
OK
redis> INCR user_id
QUEUED
redis> INCR user_id
QUEUED
redis> INCR user_id
QUEUED
redis> PING
QUEUED
redis> EXEC
1) (integer) 1
2) (integer) 2
3) (integer) 3
4) PONG
# Example 2: monitor key, And the transaction executed successfully
redis> WATCH lock lock_times
OK
redis> MULTI
OK
redis> SET lock "huangz"
QUEUED
redis> INCR lock_times
QUEUED
redis> EXEC
1) OK
2) (integer) 1
# Example 3: monitor key, And the transaction is interrupted
redis> WATCH lock lock_times
OK
redis> MULTI
OK
redis> SET lock "joe" # At this moment , Another client modified lock_times Value
QUEUED
redis> INCR lock_times
QUEUED
redis> EXEC # because lock_times Be modified , joe Transaction execution failed for
(nil)
2.1.3、discard: Cancel the business
Cancel the business , Give up executing all commands within the transaction block .
Return value :
Always returns OK .
Example
redis> MULTI
OK
redis> PING
QUEUED
redis> SET greeting "hello"
QUEUED
redis> DISCARD
OK
3、 Wrong handling of transactions
3.1、 situation 1: Wrong command in team formation , Cause all commands to cancel execution
Error report for a command in the queue , All commands in the whole queue will be canceled when executing .

The sample code is as follows , In the transaction 3 individual set command , And the first 3 An order set address There is a problem with the command itself , Failed to join queue , Finally, execute exec When , All commands are cancelled .
127.0.0.1:6379> flushdb
OK
127.0.0.1:6379> multi # Open a transaction block
OK
127.0.0.1:6379(TX)> set name ready
QUEUED
127.0.0.1:6379(TX)> set age 30
QUEUED
127.0.0.1:6379(TX)> set address # There's something wrong with the order , This causes the queue to fail
(error) ERR wrong number of arguments for 'set' command
127.0.0.1:6379(TX)> exec # perform exec When , All commands in the transaction are cancelled
(error) EXECABORT Transaction discarded because of previous errors.
3.2、 situation 2: There is no problem in team formation , Partial success and partial failure during execution
There is no problem in the process of ordering the team , Errors during execution will lead to partial success and partial failure .

The sample code is as follows , There are in the transaction 3 An order ,3 All commands are queued successfully , perform exec When ordered ,1 and 3 The command succeeded , The first 2 A failure
127.0.0.1:6379> multi
OK
127.0.0.1:6379(TX)> set k1 v1 # command 1: Set up k1 The value of is v1
QUEUED
127.0.0.1:6379(TX)> incr k1 # command 2:k1 Increasing the value of the 1, because k1 The value of is not a number , The execution will fail
QUEUED
127.0.0.1:6379(TX)> set k2 v2 # command 3: Set up k2 The value of is v2
QUEUED
127.0.0.1:6379(TX)> exec # Carry out orders ,1 and 3 The order was successful , The first 2 A failure
1) OK
2) (error) ERR value is not an integer or out of range
3) OK
127.0.0.1:6379> mget k1 k2 # see k1 and k2 Value
1) "v1"
2) "v2"
4、 The problem of transaction conflict
4.1、 Example
Imagine a scene :
There is only... In your account 10000, There are multiple people using your account , At the same time, go to the double 11 rush
A request wants to reduce the amount 8000
A request wants to reduce the amount 5000
A request wants to reduce the amount 1000

3 Requests come at the same time ①, The balance you see is 10000, Greater than the operation amount , To modify the balance , Finally, the amount becomes -4000, This is obviously problematic .
4.2、 Pessimistic locking

Pessimistic locking (Pessimistic Lock), seeing the name of a thing one thinks of its function , Is very pessimistic , Every time I go to get the data, I think others will modify it , So every time I get the data, I lock it , In this way, other people will get the data block Until it gets the lock . A lot of this locking mechanism is used in traditional relational databases , For example, line locks. 、 Table locks 、 Read the lock 、 Write locks, etc. , It's all locked before the operation .
4.3、 Optimism lock

Optimism lock (Optimistic Lock), seeing the name of a thing one thinks of its function , Is very optimistic , Every time I go there, I think that others will not modify the data , So it won't lock , However, during the modification, we will judge whether others have updated the data during this period , You can use mechanisms like version numbers . Optimistic lock is suitable for multi read applications , This can improve throughput .redis Is to use this check-and-set The mechanism implements the .
4.4、watch key [key ...]
In execution multi Before , Execute first watch key1 [key2 ...], You can monitor one or more key, If in the exec Before the command key The corresponding value has been changed by other commands , Then all commands in the transaction will be interrupted , That is, the transaction operation will be canceled .
Example
Turn on 2 A window , Execute the corresponding commands in different windows according to the time points in the following table , Pay attention to the results .
| moment | window 1 | window 2 |
| T1 | flushdb | |
| T2 | set balance 100 | |
| T3 | watch balance | |
| T4 | multi | |
| T5 | set name ready | incrby balance 50 |
| T6 | incrby balance 10 | get balance |
| T7 | exec | |
| T8 | get balance | |
| T9 | get name |
window 1 in , Yes balance Monitored , That is to say, in the implementation of watch balance After the command , stay exec Before the command , If there are other requests for balance It's been modified , So window 1 All commands in the transaction will be cancelled .
window 1 watch balance after , because T5 Time window 2 Yes balance It's been modified , Cause the window to 1 A command in the transaction has been cancelled .
window 1 The results are as follows
127.0.0.1:6379> flushdb # Empty db, Convenient test
OK
127.0.0.1:6379> set balance 100 # Set up balance The value of is 100
OK
127.0.0.1:6379> watch balance # monitor balance, if balance Modified by other commands during the transaction phase , Transaction execution will be canceled
OK
127.0.0.1:6379> multi # Open transaction
OK
127.0.0.1:6379(TX)> set name ready # Set up name The value of is ready
QUEUED
127.0.0.1:6379(TX)> incrby balance 10 # take balance Value +10
QUEUED
127.0.0.1:6379(TX)> exec # Perform transactions , because balance By window 2 Revised , Therefore, the execution of this transaction failed , return nil
(nil)
127.0.0.1:6379> get balance # obtain balance, The original value is 100, By window 2 added 50, The result is 150
"150"
127.0.0.1:6379> get name # obtain name Value , Transaction set name unsuccessful , therefore name No,
(nil)
window 2 Execution results
127.0.0.1:6379> incrby balance 50 #balance atom +50
(integer) 150
127.0.0.1:6379> get balance # obtain balance Value , by 150
"150"
4.5、unwatch: Cancel surveillance
Cancel WATCH Command to all key Surveillance .
If in execution WATCH After the command , EXEC Order or DISCARD If the order is executed first , Then there's no need to execute UNWATCH 了 .
because EXEC The command will execute the transaction , therefore WATCH The effect of the command has been produced ; and DISCARD The command cancels the transaction and cancels all of the key Surveillance , So after these two commands are executed , There's no need to implement UNWATCH 了 .
redis> WATCH lock lock_times
OK
redis> UNWATCH
OK
5、redis Three characteristics of transaction
5.1、 Separate isolation operation
All commands in the transaction are serialized 、 To execute in order , The transaction is in progress , Will not be interrupted by command requests from other clients .
5.2、 There is no concept of isolation level
The command in the queue was not submitted (exec) Before , Will not actually be implemented , Because no instruction is actually executed before the transaction is committed .
5.3、 Atomicity is not guaranteed
If a command fails in a transaction , Subsequent commands will still be executed , No rollback .
If in the team stage , Yes 1 A failure , It will not succeed later ; If you succeed in team formation , There is a command failure in the execution phase, just this failure , Other commands are executed normally , There is no guarantee of success or failure .
边栏推荐
- 两两交换链表中的节点[单向链表不断链原则]
- CF736 D2
- Niuke challenge 53e problem solution & Notes on learning with flowers and trees
- IO之ByteStream案例
- Certificate issuance process on aliyun OS (certbot)
- 奋斗吧,程序员——第五十章 海内存知己,天涯若比邻
- R language performs two sample t-test on the specified covariates based on the with function, and the t.test function performs Welch two sample t-test analysis and two independent sample t-test on the
- 奋斗吧,程序员——第四十五章 柔情似水,佳期如梦
- The R language uses the matchit package for propensity matching analysis and match The data function builds the matched sample set, uses the LM function to build the linear regression model for the ma
- Matlab的KNN分类使用(附源码),实现像素分类(自己设置训练集比例),打印测试精度
猜你喜欢

PHP database mysql question

Security risks exist in open source code: an average of 49 vulnerabilities exist in a project
![[CISCN2019 总决赛 Day1 Web4]Laravel1](/img/99/4eb4d9447ac191fb9320cd8135f019.png)
[CISCN2019 总决赛 Day1 Web4]Laravel1

Duanyongping, the "Buffett of China": a wise investment
![[2206] An Improved One millisecond Mobile Backbone](/img/75/b040f4b88050937dee57003b62f7b0.png)
[2206] An Improved One millisecond Mobile Backbone

Pychart debugging is stuck and connected appears

二叉树的前序、中序、后序遍历的两种实现

Matlab的KNN分類使用(附源碼),實現像素分類(自己設置訓練集比例),打印測試精度

俞敏洪称未来可能开电商学院;马斯克儿子申请断绝父子关系;饿了么回应大量用户收到免单信息;B站上线付费视频...

配置GPU版本的pytorch和torchvision,初学GPU版本torch踩坑
随机推荐
Realization of simple particle effect in canvas
Reader case of IO
Explanation of 94F question in Niuke practice match
本地裸文件包含
[Software Engineering] Introduction & process and life cycle modeling
Solution to the 55D problem of Niuke challenge
奋斗吧,程序员——第四十六章 此情可待成追忆,只是当时已惘然
Configure the GPU version of pytorch and torchvision, and learn the GPU version of torch step
Install pyGame
Take Wei Lai to court. What's Audi's hurry?
CF751E Phys Ed Online
【2022暑期】【LeetCode】31. 下一个排列
牛客练习赛94F题解
牛客挑战赛55E题解
Idr Display function obtains the summary statistical information of Poisson regression Poisson model (initial event density ratio IDR value, adjusted event density ratio IDR value and its confidence i
The use of cellstr function in MATLAB
【软工】 软件体系结构
[2206] An Improved One millisecond Mobile Backbone
把蔚来告上法庭,奥迪急什么?
Redis - 9、持久化之AOF(Append OnlyFile)