当前位置:网站首页>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
边栏推荐
- Installing mysql-5.7 for Linux (centos7)
- 西南林业大学“西林链”通过工信部电子标准院功能测试 | FISCO BCOS案例
- [popular science video] what is a lens antenna?
- Loop loop and CX
- Operation of simulated examination platform of diazotization process examination question bank in 2022
- Redis集群更换节点IP后如何恢复集群并保留完整集群数据
- “中国东信杯”广西大学第四届程序设计竞赛(同步赛)
- JSON conversion: entity classes and jsonobject are converted to each other, and list and jsonarray are converted to each other (fastjson version)
- "It's safer to learn a skill!" The little brother of Hangzhou campus changes to software testing, and likes to mention 10k+ weekend!
- 混泥土(地面+墙面)+ 山体裂缝数据集汇总(分类及目标检测)
猜你喜欢

MySQL表常用操作思维导图

混泥土(地面+墙面)+ 山体裂缝数据集汇总(分类及目标检测)

Pyinstaller packaging Exe (detailed tutorial)

Why should a redis cluster use a reverse proxy? Just read this one

MySQL实训报告【带源码】

What are the advantages of adaptive search advertising?

Fatal error in launcher: unable to create process using

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!

华为联运游戏或应用审核驳回:应用检测到支付serviceCatalog:X6

如何让杀毒软件停止屏蔽某个网页?以GDATA为例
随机推荐
阿里云oss文件上传系统
Point cloud perception algorithm interview knowledge points (I)
[learn FPGA programming from scratch -20]: quick start chapter - operation steps 4-2-quick use of Altera quartz II tool (Modelsim co simulation, program download to altera development board)
How to locate keywords to make advertising accurate.
混泥土(地面+墙面)+ 山体裂缝数据集汇总(分类及目标检测)
Redis startup and shutdown commands
C asynchronous programming from simple to deep (III) details awaiter
Annotate your own point cloud dataset with labelcloud open source tool as a tutorial of Kitti annotation format (support PCD and bin point clouds)
Modification of system module information of PHP security development 12 blog system
pip运行报错:Fatal error in launcher: Unable to create process using
PyGame alien invasion
“还是学一门技术更保险!”杭州校区小哥哥转行软件测试,喜提10K+双休!
如何最大化的利用各种匹配方式? ——Google SEM
Wechat applet - a case of comparing the size of numbers
Introduction to prism framework - Modular introduction
Why do we use Google search ads?
Watermelon video synchronization Tiktok also has benefits ~ the official "China Video Partner Program"
How to stop anti-virus software from blocking a web page? Take gdata as an example
Leetcode 55 jump game
Comprehensive quality of teaching resources in the second half of 2019 - subjective questions