zookeeper分布式锁服务

创建zookeeper客户端

 private CountDownLatch countDownLatch = new CountDownLatch(1);
 ZooKeeper zooKeeper;

 public ZooLock(){
     try{
         zooKeeper = new ZooKeeper("127.0.0.1:2181", 3000, new Watcher() {
             @Override
             public void process(WatchedEvent event) {
                 if (event.getType() == EventType.None) {
                     if (event.getState() == KeeperState.SyncConnected) {
                         System.out.println("connect success");
                         countDownLatch.countDown();
                     }
                 }
             }
         });
         countDownLatch.await();
     }catch (Exception e){
         System.out.println("e= "+e.getMessage());
     }
 }

获取锁

private static String LOCK_ROOT_PATH = "/locks";

private static String LOCK_NODE_NAME = "lock_";

private String lockPath;
//获取锁

public void tryLock() throws KeeperException, InterruptedException {
    createNode();

    lock();
}

Watcher watcher = new Watcher() {
    @Override
    public void process(WatchedEvent event) {
        if (event.getType()== EventType.NodeDeleted) {
            synchronized (this){
                notify();
            }
        }
    }
};


private void createNode() throws KeeperException, InterruptedException {
    //判断根节点是否存在
    Stat stat = zooKeeper.exists(LOCK_ROOT_PATH, false);
    if (stat == null) {
        zooKeeper.create(LOCK_ROOT_PATH, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }
    //创建临时有序节点
    lockPath = zooKeeper.create(LOCK_ROOT_PATH+"/"+LOCK_NODE_NAME, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
     System.out.println("节点创建成功"+lockPath);
}

private void lock() throws KeeperException, InterruptedException {
    List<String> list = zooKeeper.getChildren(LOCK_ROOT_PATH,false);
    Collections.sort(list);
    int index = list.indexOf(lockPath.substring(LOCK_ROOT_PATH.length()+1));
    if (index == 0){
        return;
    }else {
        //上一个节点的路径
        String lastPath = list.get(index - 1);
        Stat stat = zooKeeper.exists(LOCK_ROOT_PATH+"/"+lastPath, watcher);
        if (stat == null) {
            lock();
        }else {
            synchronized (watcher){
                watcher.wait();
            }
            lock();
        }
    }
}

释放锁

 public void releaseLock() throws KeeperException, InterruptedException {
        zooKeeper.delete(lockPath, -1);

        zooKeeper.close();

        System.out.println("锁已经释放.");
    }

测试

 public void sellWithLock() throws KeeperException, InterruptedException {
        ZooLock zooLock = new ZooLock();
        zooLock.tryLock();
        sell();
        zooLock.releaseLock();
    }

 private void sell() {
  System.out.println("start sell");
     try {
         TimeUnit.SECONDS.sleep(5);
     } catch (InterruptedException e) {
         e.printStackTrace();
     }
     System.out.println("end sell");

 }

 public static void main(String[] args) throws KeeperException, InterruptedException {
     TickSeller tickSeller = new TickSeller();
     for (int i = 0; i < 10; i++) {
         tickSeller.sellWithLock();
     }
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值