Zookeeper分布式锁代码实现(Java)全网最简单易懂 注释杠杠的
public class ZookeeperDistributedLock{
public Zookeeper zk = new Zookeeper("127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183",5000 watchedEvent -> watchedEvent.getPath());
public ZookeeperDistributedLock() throws IOException {}
public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
Zookeeper zk = new Zookeeper("127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183",5000 watchedEvent -> watchedEvent.getPath());
Thread.sleep(2000);
if(zk != null) {
if (null == zk.exists("/member", false)) {
zk.create("/member/" + path, "".getBytes(StandardCharsets.UTF_8),
ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
}
for (int i = 0; i < 10; i++) {
new Thread(() -> {
ZLock zlock = new ZLock();
boolean flg = zlock.getLock(zk,"lisi");
if (flg) {
try {
zlock.unLock(zk);
}catch (InterruptedException e) {
e.printStackTrace();
}catch (KeeperException e) {
e.printStackTrace();
}
}
}).start();
}
}
}
}
class ZLock {
public String currpath;
public boolean getLock (Zookeeper zk, String path) {
try{
String result = null;
result = zk.create("/member/" + path, "".getBytes(StandardCharsets.UTF_8),
ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);
List<String> list = zk.getChildren("/member",false);
Collections.sort(list);
this.currpath = result;
if (result.equals("/member/" + list.get(0))) {
return true;
}else {
CountDownLatch latch = new CountDownLatch(1);
for (int i = 0; i < list.size(); i++) {
if (result.equals("/member/" + ;ist.get(i))) {
Stat stat = zk.exists("/member/" + list.get(i-1), watchedEvent -> latch.countDown());
if (stat == null) {
latch.countDown();
return true;
}
break;
}
}
latch.await();
return true;
}
}catch (InterruptedException e) {
e.printStackTrace();
}catch (KeeperException e) {
e.printStackTrace();
}
return false;
}
public void unLock(Zookeeper zk) throws InterruptedException, KeeperException {
String str = this.currpath;
Stat stat = zk.exists(str, false);
if (stat != null)
zk.delete(str,stat.getAversion());
System.out.println(Thread.currentThread().getName() + str);
}