zookeeper分布式锁

  • w7_514219
    了解作者
  • 12.8KB
    文件大小
  • rar
    文件格式
  • 0
    收藏次数
  • VIP专享
    资源类型
  • 0
    下载次数
  • 2022-06-15 06:55
    上传日期
此Demo采用zookeeper实现分布式锁,相比于redis实现分布式锁更加可靠
zookeeper.rar
内容介绍
package com.mtxy.cn; import java.util.concurrent.CountDownLatch; import org.I0Itec.zkclient.IZkDataListener; public class ZookeeperDistrbuteLock extends ZookeeperAbstractLock{ private CountDownLatch countDownLatch = null; @Override protected void waitLock() { // TODO Auto-generated method stub try { IZkDataListener iZkDataListener = new IZkDataListener() { public void handleDataDeleted(String arg0) throws Exception { // TODO Auto-generated method stub //如果是删除数据节点 唤醒线程继续往下走 if(countDownLatch!=null){ countDownLatch.countDown(); } } public void handleDataChange(String arg0, Object arg1) throws Exception { // TODO Auto-generated method stub } }; //注册到zk监听中 zkClient.subscribeDataChanges(PATH, iZkDataListener); if(zkClient.exists(PATH)){ //如果节点存在则等待 countDownLatch = new CountDownLatch(1); //等待 countDownLatch.await(); } //删除事件通知 zkClient.unsubscribeDataChanges(PATH, iZkDataListener); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } @Override protected boolean tryLock() { // TODO Auto-generated method stub try { zkClient.createEphemeral(PATH); //创建成功 return true; } catch (Exception e) { // TODO: handle exception //创建临时节点失败 return false; } } }
评论
    相关推荐