思路直接上圖

實作核心兩點:
1.zookeeper的WatchedEvent監聽事件
2.zookeeper儲存節點資料的兩個特點。有序和臨時
基本核心代碼(簡單粗暴,很多細節沒有考慮):
public class DistributedClientLock {
// 會話逾時
private static final int SESSION_TIMEOUT = 2000;
// zookeeper叢集位址
private String hosts = "mini1:2181,mini2:2181,mini3:2181";
private String groupNode = "locks";
private String subNode = "sub";
private boolean haveLock = false;
private ZooKeeper zk;
// 記錄自己建立的子節點路徑
private volatile String thisPath;
/**
* 連接配接zookeeper
*/
public void connectZookeeper() throws Exception {
zk = new ZooKeeper(hosts, SESSION_TIMEOUT, new Watcher() {
public void process(WatchedEvent event) {
try {
// 判斷事件類型,此處隻處理子節點變化事件
if (event.getType() == EventType.NodeChildrenChanged && event.getPath().equals("/" + groupNode)) {
//擷取子節點,并對父節點進行監聽
List<String> childrenNodes = zk.getChildren("/" + groupNode, true);
String thisNode = thisPath.substring(("/" + groupNode + "/").length());
// 去比較是否自己是最小id
Collections.sort(childrenNodes);
if (childrenNodes.indexOf(thisNode) == 0) {
//通路共享資源處理業務,并且在處理完成之後删除鎖
doSomething();
//重新注冊一把新的鎖
thisPath = zk.create("/" + groupNode + "/" + subNode, null, Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}});
// 1、程式一進來就先注冊一把鎖到zk上
thisPath = zk.create("/" + groupNode + "/" + subNode, null, Ids.OPEN_ACL_UNSAFE,
CreateMode.EPHEMERAL_SEQUENTIAL);
// wait一小會,便于觀察
Thread.sleep(new Random().nextInt(1000));
// 從zk的鎖父目錄下,擷取所有子節點,并且注冊對父節點的監聽
List<String> childrenNodes = zk.getChildren("/" + groupNode, true);
//如果争搶資源的程式就隻有自己,則可以直接去通路共享資源
if (childrenNodes.size() == 1) {
doSomething();
thisPath = zk.create("/" + groupNode + "/" + subNode, null, Ids.OPEN_ACL_UNSAFE,
CreateMode.EPHEMERAL_SEQUENTIAL);
}
}
/**
* 處理業務邏輯,并且在最後釋放鎖
*/
private void doSomething() throws Exception {
try {
System.out.println("gain lock: " + thisPath);
Thread.sleep(2000);
// do something
} finally {
System.out.println("finished: " + thisPath);
//業務執行完後,删除目前節點,釋放鎖
zk.delete(this.thisPath, -1);
}
}
public static void main(String[] args) throws Exception {
DistributedClientLock dl = new DistributedClientLock();
dl.connectZookeeper();
Thread.sleep(Long.MAX_VALUE);
}
}