<>(1) The difference between distributed lock and distributed transaction

1. Distributed lock is in the cluster environment , It is used to control the access of different machines to global shared resources .
2. Distributed transaction is in the cluster environment , It is used to ensure the consistency of global transactions , Ensure that the data of multiple databases can be transferred from one consistent state to another .

<>(2) Distributed lock application scenarios

In one of us jvm In the application , If a shared variable needs multi thread synchronous access , have access to java Multi thread synchronization tool , for example ReentrantLock,Synchronized wait . But when our system evolves from single machine deployment to distributed cluster system , On different machines, the concurrency control lock policy of the original single machine will be invalid , In this case, we need to introduce distributed lock .

Take a simple example , For example, a certain takeaway Knight needs to buy an insurance every day , One day when I was buying insurance , The knight hit the buy insurance button several times , There is no control on the front end , As a result, multiple insurance requests were sent to the server at the same time , That would cause the knight to buy insurance many times , To solve this problem , We can use distributed locks , Guarantee a certain period of time , Only one machine can carry out the insurance operation , This will protect the knight from buying insurance many times . There are three main ways to implement distributed lock :

* Implementation based on Database
* be based on redis realization
* be based on ZooKeeper realization
<>(3) Implementation of distributed lock
<>1. Implementation based on Database
We can implement distributed locks through database tables , The table structure is as follows :
Each record in the table represents a lock , When we need to obtain the lock, we will query the database whether there is a record of the shared resource .

(1) If yes, get the node_info, Compare with your own machine information , If you find that it is a lock that you have already acquired , Then use shared resources directly , take count Number plus 1, After using the data, the count Subtraction 1, When count The number is 0 Delete the record . Otherwise, an error message is returned , Indicates that someone has acquired the lock .
(2) If not, create a record , Set up your own record , And record their own machine information , Then use shared resources .

In fact, the above is a simple way to use database to realize lock . There are serious problems in this way :1. There may be a single point in the database machine ,2. There is no timeout , After the database is down, the lock may not be obtained ,3. A database is a disk file , The time and performance of lock acquisition is not good .
<>2. be based on redis realization
be based on redis Distributed locks for , Mainly depends on redis Several orders of :

* setnx():set if not exists, It has two main parameters setnx(key, value). The method is atomic , If key
non-existent , Set the current key success , return 1; If the current key Already exists , Set the current key fail , return 0.
* expire():expire Set expiration time , It should be noted that setnx Command cannot be set key Timeout for , Only through expire() Right key set up .
How to use it :
1,setnx(lockkey, 1) If you return 0, The lock acquisition fails ; If you return 1, The lock is successfully obtained .
2,expire() Command pair lockkey Set timeout , In order to avoid deadlock .
3, After executing the business code , It can be done through delete Command delete key.

Usage problems :
The above usage can meet most of our business needs , But in some extreme cases , There will still be problems .

* problem : When node A End of execution setnx after , node A It went down , We haven't had time to implement it expire, This will cause other nodes to be unable to acquire the lock all the time .

Solution : use set Order substitution setnx and expire. // NX express :key Return if it doesn't exist true, Come back when you exist false // PX express : Specified expiration time
SET lockName value NX PX
* problem :
node A Lock acquired , And set the 30 The expiration time of seconds , But for some reason, business code has been executed for a long time ( More than 30 second ),delete The operation has not been performed yet . This is because of the node A The lock obtained has expired , node B Lock acquired , And the node A Yes delete operation , Node released B Lock of .

Solution : In passing delete Determine whether the current lock is added by itself before releasing the lock .
Of course, we can also use it RedLock,RedLock yes redis Implementation of distributed lock algorithm (RedLock), It can effectively prevent single point failure
. In addition, it is based on Zookeeper Implementation of , about Zookeeper I don't know much , So I won't write it here .

©2019-2020 Toolsou All rights reserved,
Send love - A little romance for programmers VHDL—— Design of frequency divider Python Implementation of Hanoi Tower code It's over , Starting salary 30khtml+css+js Make a simple website home page QQ Login interface implementation Hill sorting of sorting algorithm ——c++ realization 【 Wechat applet learning 】 Netease music cloud code page implementation details Resume the 13th session python Blue Bridge Cup 2022 Solution to the 13th Blue Bridge Cup ( whole )