Design ideas and implementation of zookeeper distributed locks

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:

  1. 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
  2. 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.
  3. 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
  4. 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)
  5. Monitor the client to re-execute the second step of logic to determine whether it has obtained the lock

The distributed unique id of zookeeper and the case github link of the distributed configuration center welcome star

code show as below

package com.sofency.top;

import org.apache.zookeeper.*;

Guess you like

Origin blog.csdn.net/qq_43079376/article/details/108696737