zookeeper实现的分布式锁

 在分布式系统中,多个jvm对共享资源进行操作时候,要加上锁,这就是分布式锁

利用zookeeper的临时节点的特性,可以实现分布式锁

public class ZookeeperDistrbuteLock extends ZookeeperAbstractLock {

    @Override
    boolean tryLock() {
        try {
            zkClient.createEphemeral(lockPath);
            return true;
        } catch (Exception e) {
            return false;
        }

    }

    @Override
    void waitLock() {

        // 使用zk临时事件监听
        IZkDataListener iZkDataListener = new IZkDataListener() {

            public void handleDataDeleted(String path) throws Exception {
                if (countDownLatch != null) {
                    countDownLatch.countDown();
                }
            }

            public void handleDataChange(String arg0, Object arg1) throws Exception {

            }
        };
        // 注册事件通知
        zkClient.subscribeDataChanges(lockPath, iZkDataListener);
        if (zkClient.exists(lockPath)) {
            countDownLatch = new CountDownLatch(1);
            try {
                countDownLatch.await();
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
        // 监听完毕后,移除事件通知
        zkClient.unsubscribeDataChanges(lockPath, iZkDataListener);
    }

}

项目结构:

github下载地址:https://github.com/jake1263/zookeeper-lock

posted @ 2019-07-25 10:47  踏月而来  阅读(223)  评论(0编辑  收藏  举报