溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Zookeeper分布式鎖實(shí)例操作

發(fā)布時(shí)間:2021-09-01 07:20:31 來源:億速云 閱讀:99 作者:chen 欄目:云計(jì)算

這篇文章主要講解了“Zookeeper分布式鎖實(shí)例操作”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“Zookeeper分布式鎖實(shí)例操作”吧!

/**
 * 包名:com.lencee.demo.zookeeper.locks
 * 文件名:LockClient.java
 * 版本信息:
 * 日期:2015年1月23日-下午4:49:48
 * 
 */
package com.lencee.demo.zookeeper.locks;
import java.util.Collections;
import java.util.List;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
/**
 * 
 * <p>TODO:類名稱<p>
 * <p>TODO:描述本類實(shí)現(xiàn)的功能作用,若為接口應(yīng)該聲明調(diào)用地址</p>
 * @version 2015年1月23日 下午4:49:48
 * 
 */
public class LockClient {
 // Zookeeper集群服務(wù)地址與端口
 private static String zkUrl = "192.168.0.101:11001";
 // 配置結(jié)點(diǎn)根路徑
 private final static String ROOT_LOCK = "/lock";
 private final static String WAIT_LOCK = "/lockwait";
 
 private final static String SELF_PATH = "/client";
 private final static String SELF_DATA = "/client";
 
 private ZooKeeper zk = null;
 private boolean iswait = true;
 //鎖路徑
 private String lockPath;
 //等待路徑
 private String selfWaitPath;
 //監(jiān)聽前置鎖路徑
 private String waitPath;
 
 public LockClient(){
  try {
   ZooKeeper zk = new ZooKeeper(zkUrl,3000,new Watcher(){
    @Override
    public void process(WatchedEvent event) {
     try {
      if(event.getType()==EventType.NodeDeleted){
       System.out.println(event.getPath()+":"+waitPath);
       getLock();
      }
     } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }});
   
   while (zk.getState() != ZooKeeper.States.CONNECTED) {
    //System.out.println("connecting:"+zk.getState());
    Thread.sleep(3000);
   }
   
   this.zk = zk;
   
   //創(chuàng)建根結(jié)點(diǎn)
   String rootValue = "分布式鎖";
   if(zk.exists(ROOT_LOCK, true)==null){
    zk.create(ROOT_LOCK, rootValue.getBytes(), Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
   }
   if(zk.exists(WAIT_LOCK, true)==null){
    zk.create(WAIT_LOCK, rootValue.getBytes(), Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
   }
   
   //在鎖結(jié)點(diǎn)上增加子結(jié)點(diǎn)
   this.lockPath = addNode(ROOT_LOCK+SELF_PATH,SELF_DATA.getBytes(),CreateMode.EPHEMERAL_SEQUENTIAL);
   
   //在等待結(jié)點(diǎn)上增加子結(jié)點(diǎn)
   this.selfWaitPath = WAIT_LOCK+this.lockPath.substring(ROOT_LOCK.length());
   addNode(this.selfWaitPath,SELF_DATA.getBytes(),CreateMode.EPHEMERAL);
   
   
   System.out.println("lockpath:"+this.lockPath);
   System.out.println("selfWaitPath:"+this.selfWaitPath);
   
   System.out.println("waitPath:"+this.waitPath);
  } catch (Exception e) {
   e.printStackTrace();
  } 
 }
 public void getLock() throws Exception {
  //檢查本線程是否取到鎖
  List<String> list = zk.getChildren(ROOT_LOCK, false);
  Collections.sort(list);
  for(String child:list){
   System.out.println(child);
  }
  
  String lookfor = this.lockPath.substring(ROOT_LOCK.length()+1);
  System.out.println(lookfor);
  
  int index = list.indexOf(lookfor);
  if(index==-1){
   System.out.println("NND,別坑我");
  }else if(index==0){
   //獲取到鎖
   System.out.println("do something...");
   //刪除鎖隊(duì)列
   //zk.delete(this.lockPath, -1);
   
   //刪除等待隊(duì)列
   //zk.delete(this.selfWaitPath, -1);
   
   this.iswait = false;
  }else{
   //未取到鎖,偵聽前一個(gè)節(jié)點(diǎn)
   String waitLockPath = list.get(index-1);
   this.waitPath = WAIT_LOCK+"/"+waitLockPath;
   zk.getData(this.waitPath, true, new Stat());
   System.out.println("沒取到鎖,偵聽"+this.waitPath);
  }
 }
 public String addNode(String path,byte[] data,CreateMode createMode) throws Exception{
  String nodePath = null;
  if(!path.startsWith("/")){
   throw new Exception("傳入的路徑?jīng)]有以'/'開始");
  }
  if(this.zk.exists(path, true)==null){
   //結(jié)點(diǎn)不存在
   nodePath = this.zk.create(path, data, Ids.OPEN_ACL_UNSAFE, createMode);
  }
  return nodePath;
 }
 
 
 /**
  * iswait
  *
  * @return  the iswait
  * @since   1.0.0
  */
 public boolean isIswait() {
  return iswait;
 }
 /**
  * @param iswait the iswait to set
  */
 public void setIswait(boolean iswait) {
  this.iswait = iswait;
 }
 public static void main(String[] args) throws Exception {
  LockClient lc = new LockClient();
  System.out.println("初始化結(jié)束。。。。。");
  Thread.sleep(20*1000);
  lc.getLock();
  while(lc.isIswait());
 }
}

感謝各位的閱讀,以上就是“Zookeeper分布式鎖實(shí)例操作”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對(duì)Zookeeper分布式鎖實(shí)例操作這一問題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI