当前位置:网站首页>The most comprehensive redis transaction control in 2022 (with illustration)
The most comprehensive redis transaction control in 2022 (with illustration)
2022-06-12 01:54:00 【Xiao Zhong wants to learn!!!】
Redis Transaction control
Concept of transactions
redis A transaction is a queue of command execution , Wrapping a set of predefined commands as a whole ( A line ). When performing , One time, in order of addition , There will be no interruption or interference in the middle .
In a queue , Disposable 、 Sequence 、 To execute a series of orders exclusively
1、 The basic operation of a transaction
Open transaction
multi
effect : Set the start position of the transaction , After this instruction is executed , All subsequent instructions are added to the transaction
Perform transactions
exec
effect : Set the end position of the transaction , Execute transactions at the same time . And multi Pairs appear , Use in pairs
Be careful : The command to join the transaction temporarily enters the task queue , Not immediately , Only execute exec It's the order that begins
Cancel the business
discard
effect : Terminate the definition of the current transaction , It happened in multi after ,exec Before
If you cancel the transaction and then execute exec Will prompt
(error) ERR EXEC without MULTIerror message
2、 Transaction considerations
Syntax input error
- It means that the command writing grammar is incorrect
- If there is a syntax error in the command contained in the defined transaction , All commands in the overall transaction will not be executed . Including commands with correct syntax .
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-s2RBw7lj-1654951860804)(images/image-20220611192923695.png)]](/img/f5/017059abca61f3c6a6214dee30c54b.png)
Running error
- Indicates that the command format is correct , But it can't be executed correctly . For example list Conduct incr operation
- Commands that run correctly execute , Running the wrong command will not be executed
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-rw3EidUF-1654951860805)(images/image-20220611193144874.png)]](/img/08/bbf84ccf21a9ba64e4eb07a95f4625.png)
Be careful : The data corresponding to the executed command will not be rolled back automatically , The programmer needs to implement rollback in the code
Manual transaction rollback
- Record the status before the data affected during the operation
- Single data :string
- More data :hash、list、set、zset
- Set the command to restore all modified items
- Single data : direct set( Pay attention to the surrounding properties , For example, timeliness )
- More data : Modify the corresponding value or clone and copy as a whole
- Record the status before the data affected during the operation
3、 Transaction execution based on specific conditions 【 Transaction lock 】
Business scenario
Tmall double 11 During the hot sale , Replenish the sold out goods ,4 Every salesman has the right to replenish . Replenishment may be a series of operations , Multiple continuous operations are involved , How to ensure that the operation will not be repeated ?
Business analysis
- It is possible for multiple clients to operate on the same set of data at the same time , And once the data is modified by the operation , Will not apply to continue operation
- Lock the data to be manipulated before the operation , As soon as it changes , Terminate the current operation
Solution
Yes key Add monitoring lock , In execution exec If key There is a change , Terminate transaction execution
watch key1 [key2……]![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-sN6ucqVc-1654951860806)(images/image-20220611195835692.png)]](/img/8c/45f1b965fb001fa86206d11d6134c8.png)
obtain name by nil Why :
- Modified in other clients name value
- watch A change in value was detected and the transaction was terminated
- The value obtained after exiting the transaction is the value modified by the second client
Cancel for all key Surveillance
In the monitored key If it is modified, the transaction will be finalized , If you cancel monitoring, modifying the original monitored value will not affect the transaction execution
unwatch
4、 Transaction execution based on specific conditions 【 Distributed lock 】
Business scenario
Tmall double 11 During the hot sale , Replenish the sold out goods , And the replenishment is completed . Customers are enthusiastic about buying ,3 Buy all goods in seconds . The inventory has been completely emptied in this replenishment , How to prevent the last item from being purchased by more than one person at the same time ?【 Oversold problem 】
Business analysis
- Use watch Monitor one key Is there any change that can't solve the problem , The specific data to be monitored here
- although redis It's single threaded , But when multiple clients operate on the same data at the same time , How to avoid not being modified at the same time ?
Solution
Use setnx Set a public lock
setnx lock-key valueutilize setnx The return value characteristic of the command , If there is a value, the setting fails , If there is no value, the setting is successful
- For the return setting successful , Have control , Carry out specific business operations in the next step
- For return settings that failed , No control , To line up or wait for
After the operation, pass
delOperate the release lock
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-rEjCO0pk-1654951860807)(images/image-20220611202958993.png)]](/img/c9/5dc042014d43be2faecd376f6f67d2.png)
Be careful : The above solution is a design concept , Rely on norms to ensure , Risky
5、 Transaction execution based on specific conditions 【 Distributed locks improve time limits 】
Business scenario
Mechanisms that rely on distributed locks , When a user operates, the corresponding client goes down , And the lock has been obtained at this time . How to solve ?
Business analysis
- Since the lock operation is controlled by the user, lock and unlock , There must be a risk of not unlocking after locking
- The unlocking operation that needs to be performed cannot rely solely on user control , At the system level, the corresponding minimum treatment scheme shall be given
Solution
Use expire For lock key Add time limit , Don't release , Abandon lock
// Add a time limit to the lock ( second )
expire lock-key second
// Add a time limit to the lock ( millisecond )
pexpire lock-key milliseconds
Because operations are usually microseconds or milliseconds , Therefore, the locking time should not be set too large . The specific time needs to be confirmed after business test
- for example : The longest execution time for holding a lock 127ms, The shortest execution time 7ms.
- Testing the maximum execution time of a million times corresponds to the maximum time consumption of a command , Testing millions of network delays takes an average of
- Lock time setting is recommended : Most time consuming 120%+ Average network latency 110%
- If the business takes the most time << Average network latency , Usually it is 2 An order of magnitude , It takes a long time to take one of them
边栏推荐
- Huawei intermodal game or application review rejected: the application detected payment servicecatalog:x6
- Sogou Pinyin official website screenshot tool pycharm installation
- 螺旋矩阵(技巧)
- Manually tear the linked list (insert, delete, sort) and pointer operation
- 如何定位关键词使得广告精准投放。
- How to automatically color cells in Excel
- “还是学一门技术更保险!”杭州校区小哥哥转行软件测试,喜提10K+双休!
- Introduction to prism framework - Modular introduction
- Redis cluster + sentinel mode + replicas
- 决定广告质量的三个主要因素
猜你喜欢

MySQL高级部分知识点

pip运行报错:Fatal error in launcher: Unable to create process using

Basic use of MATLAB

Point cloud perception algorithm interview knowledge points (II)

kmeans从0到1

Concepts of programs, processes, and threads

“还是学一门技术更保险!”杭州校区小哥哥转行软件测试,喜提10K+双休!

Redis cluster + sentinel mode + replicas

In 2022, the internal promotion of the "MIHA Tour" golden, silver and silver social recruitment started in April and march! Less overtime, good welfare, 200+ posts for you to choose, come and see!

Is the bidding price fixed for each click?
随机推荐
What are the advantages of adaptive search advertising?
[learn FPGA programming from scratch -19]: quick start chapter - operation steps 4-1- Verilog software download and construction of development environment - Altera quartz II version
The resignation of the chief oracle engineer was furious: MySQL is a terrible database, so it is recommended to consider PostgreSQL!
MySQL表常用操作思维导图
Leetcode 45 jump game II
Redis实现消息队列的4种方案
2022 tool fitter (Advanced) recurrent training question bank and online simulation examination question bank source: YiDianTong official account of safety production simulation examination
Entity class dto to VO is converted through plug-in
C language programming classic games - minesweeping
广泛匹配修饰符符号已经被弃用,请勿使用
Data system provider Jidao technology joins dragon lizard community
华为联运游戏或应用审核驳回:应用检测到支付serviceCatalog:X6
Software engineering course: Chapter 2 software problem definition and feasibility analysis after class exercises
Linux(CentOS7)安裝MySQL-5.7版本
为什么我们要使用谷歌搜索广告?
Design principle [Demeter's Law]
Why should a redis cluster use a reverse proxy? Just read this one
websocket 切后台10秒后 关闭掉了
lua 函数
serialization and deserialization