当前位置:   article > 正文

zokeeper分布式锁代码实现_zookeeper分布式锁代码

zookeeper分布式锁代码

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); //防止连接不上zookeeper
        
        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 { //lock 
    public String currpath; //当前的zNode
    
    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);
    }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/498913
推荐阅读
相关标签
  

闽ICP备14008679号