This is the 13th day of my participation in the August More Text Challenge.More challenges in August
A distributed lock
In distributed environment, to ensure data consistency, distributed lock technology is used to ensure that only a fixed number of processes modify data at the same time: only the client that obtains the lock can modify data, and other clients can only wait temporarily.
Implementation method:
- The unique index of the database
- Redis SETNX instruction
- RedLock algorithm of Redis
- Temporary sequence node of ZooKeeper
Blocking locks
Blocking locks are usually implemented using mutex:
A mutex value of 0 indicates that another process is using the lock and is in the locked state. A mutex value of 1 indicates that the process is not locked. 1 and 0 can be represented by an integer value, or by the presence or absence of some data.
The unique index of the database
A record is inserted into the table when the lock is acquired and deleted when the lock is released. A unique index guarantees that the record is inserted only once, so the existence of the record can be used to determine whether the record is locked.
There are several problems
- The lock has no expiration time. If the unlock fails, other processes cannot obtain the lock.
- This lock can only be a non-blocking lock. If the lock fails to be inserted, an error will be reported and the lock cannot be retried.
- There is no reentrant, and processes that have acquired locks must also acquire them again.
Redis SETNX instruction
- Insert a key-value pair using the SETNX(Set if not exist) directive, returning False if the Key already exists, and True otherwise.
- The SETNX instruction is similar to the unique index of the database, which guarantees the existence of only one Key value pair. Therefore, the existence of a Key value pair can be used to determine whether it is stored in the locked state.
- The EXPIRE directive sets an expiration time for a key-value pair, avoiding lock release failures in the database unique index implementation.
RedLock algorithm of Redis
- Multiple Redis instances are used to achieve distributed locking, which is to ensure that in case of a single point of failure, you can still try to obtain locks from N independent Redis instances.
- The lock acquisition is considered successful only if the time is less than the lock expiration time and the lock is obtained from most (N/2+1) instances
- If the lock fails to be acquired, the lock is released on each instance.
Temporary sequence node of ZooKeeper
See this blog post for more details – How to Implement distributed locks using ZooKeeper.