java 使用zookeeper包实现zookeeper分布式锁
zookeeper不可重入锁的实现代码
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
public class DistributedLockExample {
private static final String ZOOKEEPER_CONNECTION_STRING = "localhost:2181";
private static final int SESSION_TIMEOUT = 5000;
private static final String LOCK_PATH = "/distributed_lock";
private ZooKeeper zooKeeper;
//当前最新的一个节点
private String currentZnodeName;
public DistributedLockExample() throws IOException {
this.zooKeeper = new ZooKeeper(ZOOKEEPER_CONNECTION_STRING, SESSION_TIMEOUT, new Watcher() {
@Override
public void process(WatchedEvent event) {
// Watcher实现
}
});
}
public void acquireLock() throws KeeperException, InterruptedException {
while (true) {
createLockNode();
//获取锁节点下的所有子节点
List<String> children = zooKeeper.getChildren(LOCK_PATH, false);
//排序
Collections.sort(children);
//获取小的节点,也就是最先创建的那个节点
String smallestNode = children.get(0);
//如果当前最新节点等于最小节点,那么就代表获取到了锁
if (currentZnodeName.equals(LOCK_PATH + "/" + smallestNode)) {
return;
} else {

浙公网安备 33010602011771号