Why do we have distributed locks?
For example, we want to place orders, divided into two operations, the Order of Success (orders service), deduct Inventory (goods service). If there is no lock, two requests come in at the same time. First check there is no inventory, a look has, and then place orders, reduce inventory. There must be an error. The result we want is. Only one request can come in. When the operation is complete, the next request comes in again. This is not the phenomenon of inventory selling super. At this point, we need to use distributed locks to implement.
There are many ways to implement distributed locks. REDIS,ZK is all you can. But it is recommended ZK.
First, the general idea:
First, we get the lock first when we place the order. If successful, proceed with our business process below. After the process is finished. Release the lock. The other request, if requested, also acquires the lock first, and of course it is not, so it hangs, when someone else releases it, and then tries to acquire the lock again.
How do I get a lock?
The main use of ZK to create a node implementation, that is, the first node is not, that no one acquires a lock, and then you create this node, you get this lock. Remember, this node must be a temporary node.
Then, of course, acquiring the lock this operation is a dead loop. Controlled by a static variable Countdownlatch. If Countdownlatch is greater than 0, wait hangs, and when someone else releases, another loop continues, attempting to acquire the lock.
Let's release the lock. This node is deleted. Countdownlatch Reset to 1.
The code is empty!!!! First occupy the Pit
Spring consolidates curator for distributed locks