Distributed locks can be implemented in many ways, such as through databases and redis, and zookeeper, as a distributed collaboration tool, also has a standard implementation.
Design ideas:
- Each client creates a temporary ordered node /Locks/Lock_ under /Locks. After the creation is successful, there will be a node corresponding to each client under /Locks, such as /Locks/Lock_0000000001
- The client obtains the child nodes under /Locks and sorts them to determine whether the first one is themselves.If the lock node is in the first place, it means that the lock is successfully acquired.
- If your own lock node is not in the first place, then monitor the previous lock node, for example, if you lock the node Lock_000000002, then monitor Lock_000000001
- The current technology Diamin corresponding to the lock node (Lock_000000001) is executed, and the lock is released, which will trigger the logic of the monitoring client (Lock_000000002)
- Monitor the client to re-execute the second step of logic to determine whether it has obtained the lock
code show as below
package com.sofency.top;
import org.apache.zookeeper.*;