Guest tutor: Teaching director of well-known institutions under BObo ** Front, expert of CSDN blog, used to work in Yonyou Software Power Division. ** Projects: PMIS project of China Huadian, ERP system of China Huadian Group, PMIS project of China Guodian, etc
01What are the solutions for distributed locking
MYSQL
MYSQL can be used as follows:
Each record in the database is a lock, taking advantage of the exclusivity of MySQL’s unique index. If multiple requests are submitted to the database at the same time, the database guarantees that only one operation will succeed, so we can assume that the thread that succeeded in the operation has acquired the lock of the method. When the method completes, we can delete the database record to release the lock.
Pessimistic locks use the lock method, using for UPDATE with an explicit row lock, so that you can use the row-level exclusive lock to implement distributed locks.
Optimistic locking has higher performance than pessimistic locking. Optimistic locking is not a lock, but a design idea. It is implemented using the Version logging mechanism.
Redis
Redis is selected to achieve distributed lock for several reasons
(1) Redis has high performance; (2) The Redis command supports this well and is convenient to implement.
Redis usage scenarios are particularly high in concurrency.
Ephemeral nodes are one of the types of Zookeeper nodes that have the -e attribute. The effect of that is
02How to implement distributed lock in Zookeeper
Zookeeper Distributed lock mechanism
-
Convention: obtain the lock with the smallest serial number;
-
The serial number is not the smallest, so it listens for the previous node with a smaller serial number.
-
If a node is awakened, check whether the node is awakened with the smallest serial number. If it is the smallest acquisition lock; If it is not the smallest, then listen on nodes smaller than it
03How is Redis distributed
Redis distributed lock implementation idea
(1) When obtaining the lock, use setnx to add the lock, and use the expire command to add a timeout period for the lock. When the timeout period expires, the lock will be automatically released. The value of the lock is a randomly generated UUID. (2) set a timeout time for lock acquisition. If this time is exceeded, lock acquisition will be abandoned; (3) When releasing the lock, determine whether it is the lock according to the UUID. If it is the lock, execute delete to release the lock.
Distributed lock is often used in daily Coding, but the knowledge of distributed lock is still very profound. Hopefully this article will give you a clear idea of the distributed lock solution and further improve your ability to view the source code.