1.父節點:/disLocks1(zk根目錄下的disLocks1目錄,CreateMode.PERSISTENT類型)java
2.全部須要獲取鎖的線程,都會在/disLocks1目錄下創建一個臨時順序的子節點(CreateMode.EPHEMERAL_SEQUENTIAL類型)node
3.每次都是序號最小的節點獲取鎖,當最小的節點業務邏輯處理完畢後,斷開本次鏈接(或者刪除當前子節點),則臨時順序的節點自動刪除,接着讓其餘沒有獲取鎖的節點去獲取鎖apache
每當一臺機器去建立了一個臨時順序節點,去獲取鎖失敗的時候(本節點不是序號最小的節點),則找出當前節點的前一個節點,並在該節點上註冊一個監聽事件,當前一個節點刪除(獲取鎖成功),則後一個節點當即去獲取鎖。緩存
相比於監聽父節點機制的優點:不用全部的子節點都去監聽父節點,講子節點的監聽事件均勻的分佈在了對應的兄弟子節點上,這樣在高併發的狀況下,避免了當子節點刪除的時候,父節點的監聽事件過多,父節點每次須要觸發大量的監聽事件。併發
貼代碼:分佈式
package zoo.com.zk.zoo.lock; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.concurrent.CountDownLatch; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.EventType; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.apache.zookeeper.ZooDefs.Ids; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.Stat; /** * * zk分佈式鎖實現 * 基於監聽父節點下面的所有子節點實現,效率較低 * */ public class DistributedLock2 implements Watcher{ public static String host="127.0.0.1:2181"; //緩存時間 private static final int TIME_OUT = 2000; private static String FATHER_PATH = "/disLocks1"; private ZooKeeper zk; private int threadId; protected CountDownLatch countDownLatch=new CountDownLatch(1); private String lockPath; public DistributedLock2(int threadId){ this.threadId = threadId; } public void getZkClient(String host,int timeout) { try { if(null == zk){ zk = new ZooKeeper(host, timeout, this); } } catch (IOException e) { e.printStackTrace(); } } /** * * * */ public String createNode(){ try { //檢測節點是否存在 Stat stat = zk.exists(FATHER_PATH, false); //父節點不存在,則建立父節點 if(Objects.isNull(stat)){ synchronized (FATHER_PATH) { Stat stat2 = zk.exists(FATHER_PATH, false); if(Objects.isNull(stat2)){ //父節點是持久節點 String path = zk.create(FATHER_PATH, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); System.out.println("父節點建立成功,返回值【"+path+"】"); } } } //建立持久性父節點下面的臨時順序子節點,/父節點路徑/0000000002 String lockPath = zk.create(FATHER_PATH+"/",null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); System.out.println("線程【"+threadId+"】開始執行,子節點建立成功,返回值【"+lockPath+"】"); return lockPath; } catch (KeeperException e1) { e1.printStackTrace(); } catch (InterruptedException e1) { e1.printStackTrace(); } return null; } //校驗當前節點是否爲序號最小的節點 public boolean checkLockPath(String lockPath){ try { //註冊父節點監聽事件,當父節點下面的子節點有變化,就會觸發Watcher事件 List<String> nodeList = zk.getChildren(FATHER_PATH, false); Collections.sort(nodeList); int index = nodeList.indexOf( lockPath.substring(FATHER_PATH.length()+1)); switch (index){ case -1:{ System.out.println("本節點已不在了"+lockPath); return false; } case 0:{ System.out.println("線程【"+threadId+"】獲取鎖成功,子節點序號【"+lockPath+"】"); return true; } default:{ String waitPath = nodeList.get(index - 1); zk.exists(FATHER_PATH+"/"+waitPath, this); System.out.println(waitPath+"在"+nodeList.get(index)+"點前面,須要等待【"+nodeList.get(index)+"】"); return false; } } } catch (KeeperException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return false; } public boolean getLock(){ //建立獲取鎖的節點(順序臨時節點) String childPath = createNode(); boolean flag = true; if(null != childPath){ lockPath = childPath; try { //輪詢等待zk獲取鎖的通知 while(flag){ if(checkLockPath(childPath)){ //獲取鎖成功 return true; }else{ //節點建立成功, 則等待zk通知 countDownLatch.await(); } } } catch (InterruptedException e) { e.printStackTrace(); } }else{ System.out.println("節點沒有建立成功,獲取鎖失敗"); } return false; } public void process(WatchedEvent event) { //成功鏈接zk,狀態判斷 if(event.getState() == KeeperState.SyncConnected){ //子節點有變化 if(event.getType() == EventType.NodeDeleted){ System.out.println("臨時節點自動刪除"); countDownLatch.countDown(); } } } public void unlock(){ try { zk.delete(getLockPath(), -1); zk.close(); } catch (InterruptedException e) { e.printStackTrace(); } catch (KeeperException e) { e.printStackTrace(); } } public String getLockPath() { return lockPath; } public ZooKeeper getZooKeeper(){ return zk; } public static void main(String[] args) throws KeeperException, InterruptedException { for(int i=0; i < 10; i++){ final int threadId = i+1; new Thread(){ @Override public void run() { try{ DistributedLock2 dis = new DistributedLock2(threadId); dis.getZkClient(host,TIME_OUT); if(dis.getLock()){ Thread.sleep(200); dis.unlock(); } } catch (Exception e){ System.out.println("【第"+threadId+"個線程】 拋出的異常:"); e.printStackTrace(); } } }.start(); } } }