Redis Watch mechanism realizes distributed optimistic lock

RedisUse the command in watchto determine whether the transaction will eventually be executed or rolled back. Usually, the commandmulti is used before the command to monitor some key-value pairs, and then the command is used to start the transaction and execute various commands that operate on the data structure. At this time, these commands will not be executed immediately, but enter the queue to wait for the follow-up The action to perform. ​ When using the command to execute a transaction, it will first compare the key-value pairs monitored by the command . If there is no change, it will execute the command in the transaction queue and submit the transaction; if there is a change, it will not Execute commands in any transaction without transaction rollback. No matter whether the transaction is rolled back or not, the commands before the execution of the transaction will be canceled . This process is shown in the following figure:watchmulti
RedisexecwatchRediswatch

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-Z6AWQ5ci-1661936898782)(D:\developsoftware\mayun\note\study-note\java\middleware\image\ image-20220831144828414.png)]

​ Redis uses the Watch mechanism to implement optimistic locks based on the idea of ​​CAS (Compare And Swap) (compare and replace). It is not mutually exclusive and does not consume resources due to lock waiting, but it requires repeated retries. The trial mechanism can respond faster. So we can use redis to implement optimistic locking. The specific ideas are as follows:

Guess you like

Origin blog.csdn.net/qq_36305027/article/details/126627873