Hadoop-32 ZooKeeper 分布式锁问题 分布式锁Java实现 附带案例和实现思路代码
package icu.wzk.zk.demo02;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class ClientTest {
private ZkClient zkClient = new ZkClient("h121.wzk.icu:2181,h122.wzk.icu:2181,h123.wzk.icu:2181");
String beforeNodePath;
String currentNodePath;
CountDownLatch countDownLatch = null;
public ClientTest() {
synchronized (ClientTest.class) {
if (!zkClient.exists("/lock")) {
zkClient.createPersistent("/lock");
}
}
}
public boolean tryGetLock() {
if (null == currentNodePath || currentNodePath.isEmpty()) {
currentNodePath = zkClient.createEphemeralSequential("/lock/", "lock");
}
final List<String> childs = zkClient.getChildren("/lock");
Collections.sort(childs);
final String minNode = childs.get(0);
if (currentNodePath.equals("/lock/" + minNode)) {
return true;
} else {
final int i = Collections.binarySearch(childs, currentNodePath.substring("/lock/".length()));
String lastNodeChild = childs.get(i - 1);
beforeNodePath = "/lock/" + lastNodeChild;
}
return false;
}
public void waitForLock() {
final IZkDataListener iZkDataListener = new IZkDataListener() {
@Override
public void handleDataChange(String dataPath, Object data) throws Exception {
//
}
@Override
public void handleDataDeleted(String dataPath) throws Exception {
countDownLatch.countDown();
}
};
zkClient.subscribeDataChanges(beforeNodePath, iZkDataListener);
if (zkClient.exists(beforeNodePath)) {
countDownLatch = new CountDownLatch(1);
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
zkClient.unsubscribeDataChanges(beforeNodePath, iZkDataListener);
}
public void deleteLock() {
if (zkClient != null) {
zkClient.delete(currentNodePath);
zkClient.close();
}
}
public void getLock() {
final String threadName = Thread.currentThread().getName();
if (tryGetLock()) {
System.out.println(threadName + ": 获取到了锁!");
} else {
System.out.println(threadName + ": 没有获取到锁!");
waitForLock();
// 自己调用自己
getLock();
}
}
}