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);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)