Distributed Lock Zatan

  Speaking distributed lock, we all know the basic of the three ways:

1, based on the database (unique index)
2, based on the Zookeeper 
. 3, based on the cache (Redis, memcached, tair)
 

  Let's explain each achieved under several locks distributed:

First, based on the database (unique index)

  Implementation of distributed database lock is the use of a unique index on the database to achieve, exclusive natural unique index, which is exactly in line with our requirements for locks: one time only allows a competitor to acquire the lock.

  When we insert a locking latch record in the database, using the id for anti-heavy business. When the first competitor successfully locked, the second competitor will throw again locked unique index conflict, if this exception is thrown, we determined that the current contenders lock failure.

  Anti-heavy business id need our own to define, for example, we lock object is a method, then our business anti-heavy id is the name of this method, if the lock object is a class, the business anti-replay id is the name of the class.

Second, based on Zookeeper

  zookeeper can achieve an orderly node + watch, the realization of ideas, such as:
  generates an ordered temporary node for each thread, in order to ensure orderly, once all the nodes in order, get all the nodes, each thread to determine whether his youngest If so, get a lock, perform operations finished removing its own node. If a node is not the first to listen to its previous node when a node before it is deleted, it will get the lock, and so on.

Third, based on Redis

  1, setnx way (atomicity of how to solve the Expire?)

  2、SET key value [EX seconds] [PX milliseconds] [NX|XX]

EX second: expiration time of the key to second seconds ( ✔️ ) 
PX millisecond: expiration time of the key to millisecond ms
NX: only when the bond is absent, fishes key set operation (✔️)
XX: only the key already exists in the when, fishes key to set the operation
when the sET operation is successfully completed, return OK, otherwise nil
must be noted that, to understand the maker to people, value is recommended to take uuid

  3, reentrant how to solve (threadLocal? AQS?)

  4, how to solve business Timeout (redisson?)

  

 

Guess you like

Origin www.cnblogs.com/fbw-gxy/p/11689669.html