1 zk 事件監(jiān)聽機制
1.1 watcher概念
zk 提供了消息發(fā)布/消息訂閱功能盲再。多個訂閱者同時監(jiān)聽某一個主題對象。當該主題對象發(fā)生改變(節(jié)點內(nèi)容改變,子節(jié)點列表改變等),會實時页屠、主動通知所有訂閱者。
zk采用Watcher機制來實現(xiàn)發(fā)布訂閱功能蓖柔。
該機制會在主題對象發(fā)生變化后異步通知客戶端辰企,因此客戶端不必再訂閱后輪詢阻塞,從而減輕客戶端壓力况鸣。
watcher機制與觀察者模式類似牢贸。可用看作是觀察者模式在分布式場景中的實現(xiàn)镐捧。
1.2 watcher架構(gòu)
由三部分組成:
- zk 服務端
- zk 客戶端
- 客戶端的ZKWatchManager對象
1 客戶端首先將watch注冊到服務端潜索,同時將watcher對象保存到客戶端的watcher管理器中。
2 當zk服務端監(jiān)聽的數(shù)據(jù)狀態(tài)發(fā)生變化后懂酱,服務端會主動通知客戶端竹习。
3 接著客戶端的watcher管理器會觸發(fā)相關(guān)的watcher來回調(diào)相應的處理邏
輯。
1.4 watcher的接口設計
Watcher是一個接口玩焰,任何實現(xiàn)了接口的類就是一個新的watcher由驹。watcher內(nèi)部包含了兩個枚舉類: KeeperState芍锚、EventType
package watcher;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import java.util.concurrent.CountDownLatch;
public class ZkConnectionWatcher implements Watcher {
final static CountDownLatch latch = new CountDownLatch(1);
static ZooKeeper zk;
public static void main(String[] args) {
try {
zk = new ZooKeeper("localhost:2181", 5000, new ZkConnectionWatcher());
// 阻塞等待連接創(chuàng)建
latch.countDown();
// 會話id
System.out.println(zk.getSessionId());
// 驗證鑒權(quán)失敗的事件監(jiān)聽
// 添加授權(quán)用戶
zk.addAuthInfo("digest", "wh:12344".getBytes());
byte[] res = zk.getData("/wh/node1", false, null);
System.out.println(new String(res));
Thread.sleep(10000);
zk.close();
System.out.println("all done...");
} catch (Exception e) {
}
}
public void process(WatchedEvent event) {
try {
// 監(jiān)聽連接事件類型
if (event.getType() == Event.EventType.None) {
if (event.getState() == Event.KeeperState.SyncConnected) {
System.out.println("conncetioned ...");
latch.countDown();
} else if (event.getState() == Event.KeeperState.Disconnected) {
System.out.println("connection duakai...");
} else if (event.getState() == Event.KeeperState.Expired) {
System.out.println("connection timeout");
zk = new ZooKeeper("localhost:2181", 5000, new ZkConnectionWatcher());
} else if (event.getState() == Event.KeeperState.AuthFailed) {
System.out.println("認證失敗");
}
}
} catch (Exception e) {
}
}
}
package set;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class ZkSet1 {
ZooKeeper zk;
@Before
public void before() throws IOException, InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
zk = new ZooKeeper("localhost:2181", 5000, new Watcher() {
public void process(WatchedEvent event) {
if (event.getState().equals(Event.KeeperState.SyncConnected)) {
System.out.println("connectioned ...");
latch.countDown();
}
System.out.println("path=" + event.getPath());
System.out.println("eventType=" + event.getType());
}
});
latch.await();
}
@After
public void after() throws InterruptedException {
zk.close();
}
@Test
public void watcherExist1() throws KeeperException, InterruptedException {
// arg1 : node path
// arg2 : 使用連接對象里的watcher對象
zk.exists("/wh/node1", true);
Thread.sleep(10000);
System.out.println("all done...");
}
@Test
public void watcherExist2() throws KeeperException, InterruptedException {
// arg1 : node path
// arg2 : 自定義的watcher對象
zk.exists("/wh/node1", new Watcher() {
public void process(WatchedEvent event) {
System.out.println("自定義的watcher...");
System.out.println("path=" + event.getPath());
System.out.println("eventType=" + event.getType());
}
});
Thread.sleep(10000);
System.out.println("all done...");
}
@Test
public void watcherExist3() throws KeeperException, InterruptedException {
// 驗證watcher是一次性的
Watcher watcher = new Watcher() {
public void process(WatchedEvent event) {
System.out.println("自定義的watcher...");
System.out.println("path=" + event.getPath());
System.out.println("eventType=" + event.getType());
}
};
// arg1 : node path
// arg2 : 使用連接對象里的watcher對象
zk.exists("/wh/node1", watcher);
Thread.sleep(10000);
System.out.println("all done...");
}
@Test
public void watcherExist4() throws KeeperException, InterruptedException {
// 驗證watcher是一次性的
// 改進昔园,可用重復使用
Watcher watcher = new Watcher() {
public void process(WatchedEvent event) {
System.out.println("自定義的watcher...");
System.out.println("path=" + event.getPath());
System.out.println("eventType=" + event.getType());
try {
zk.exists("/wh/node1", this);
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
// arg1 : node path
// arg2 : 使用連接對象里的watcher對象
zk.exists("/wh/node1", watcher);
Thread.sleep(10000);
System.out.println("all done...");
}
@Test
public void watcherExist5() throws KeeperException, InterruptedException {
// 注冊多個watcher
zk.exists("/wh/node1", new Watcher() {
public void process(WatchedEvent event) {
System.out.println("自定義的watcher1...");
System.out.println("path=" + event.getPath());
System.out.println("eventType=" + event.getType());
}
});
zk.exists("/wh/node1", new Watcher() {
public void process(WatchedEvent event) {
System.out.println("自定義的watcher2...");
System.out.println("path=" + event.getPath());
System.out.println("eventType=" + event.getType());
}
});
Thread.sleep(10000);
System.out.println("all done...");
}
}
類似1.6.1 exists
類似1.6.1 exists
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import watcher.ZkConnectionWatcher;
import java.util.concurrent.CountDownLatch;
public class ZkConfigCenter implements Watcher {
final static CountDownLatch latch = new CountDownLatch(1);
static ZooKeeper zk;
private String url;
private String name;
private String pwd;
public void process(WatchedEvent event) {
try {
// 監(jiān)聽連接事件類型
if (event.getType() == Event.EventType.None) {
if (event.getState() == Event.KeeperState.SyncConnected) {
System.out.println("conncetioned ...");
latch.countDown();
} else if (event.getState() == Event.KeeperState.Disconnected) {
System.out.println("connection duakai...");
} else if (event.getState() == Event.KeeperState.Expired) {
System.out.println("connection timeout");
zk = new ZooKeeper("localhost:2181", 5000, new ZkConnectionWatcher());
} else if (event.getState() == Event.KeeperState.AuthFailed) {
System.out.println("認證失敗");
} else if (event.getType() == Event.EventType.NodeDataChanged) {
initValue();
}
}
} catch (Exception e) {
}
}
public static void main(String[] args) throws InterruptedException {
ZkConfigCenter configCenter = new ZkConfigCenter();
for (int i=0;i<10;i++) {
Thread.sleep(5000);
System.out.println("url = " + configCenter.getUrl());
System.out.println("name = " + configCenter.getName());
System.out.println("pwd = " + configCenter.getPwd());
}
}
public ZkConfigCenter() {
initValue();
}
public void initValue() {
try {
zk = new ZooKeeper("localhost:2181", 5000, new ZkConnectionWatcher());
String url = new String(zk.getData("/wh/config/url", true, null));
String name = new String(zk.getData("/wh/config/name", true, null));
String pwd = new String(zk.getData("/wh/config/pwd", true, null));
} catch (Exception e) {
}
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
import org.apache.zookeeper.*;
import watcher.ZkConnectionWatcher;
import java.util.concurrent.CountDownLatch;
public class GlobalUniqueId implements Watcher {
final static CountDownLatch latch = new CountDownLatch(1);
static ZooKeeper zk;
private String nodePath = "/uniqueid";
public void process(WatchedEvent event) {
try {
// 監(jiān)聽連接事件類型
if (event.getType() == Event.EventType.None) {
if (event.getState() == Event.KeeperState.SyncConnected) {
System.out.println("conncetioned ...");
latch.countDown();
} else if (event.getState() == Event.KeeperState.Disconnected) {
System.out.println("connection duakai...");
} else if (event.getState() == Event.KeeperState.Expired) {
System.out.println("connection timeout");
zk = new ZooKeeper("localhost:2181", 5000, new ZkConnectionWatcher());
} else if (event.getState() == Event.KeeperState.AuthFailed) {
System.out.println("認證失敗");
} else if (event.getType() == Event.EventType.NodeDataChanged) {
}
}
} catch (Exception e) {
}
}
public GlobalUniqueId() {
try {
zk = new ZooKeeper("localhost:2181", 5000, new ZkConnectionWatcher());
latch.countDown();
} catch (Exception ex) {
}
}
public String getUniqueId() {
String id = "";
try {
// 創(chuàng)建臨時有序節(jié)點
id = zk.create(nodePath, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
// /uniqueid000000001
id = id.substring(9);
} catch (Exception ex) {
}
return id;
}
public static void main(String[] args) {
GlobalUniqueId globalUniqueId = new GlobalUniqueId();
for (int i=0;i<10;i++) {
System.out.println(globalUniqueId.getUniqueId());
}
}
}
import javafx.scene.SubScene;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
/**
* 利用臨時有序節(jié)點來實現(xiàn)分布式鎖
*/
public class ZkLock {
// zk url
String zkUrl = "localhost:2181";
final CountDownLatch latch = new CountDownLatch(1);
// zk 配置信息
ZooKeeper zooKeeper;
private static final String LOCK_NODE_PATH = "/Locks";
private static final String LOCK_NODE_NAME = "/Lock_";
private String lockPath;
public ZkLock () {
try {
zooKeeper = new ZooKeeper(zkUrl, 5000, new Watcher() {
public void process(WatchedEvent event) {
if (event.getType() == Event.EventType.None) {
System.out.println("connectioned ....");
latch.countDown();
}
}
});
latch.await();
} catch (Exception e) {
}
}
// 獲取鎖
public void tryAccquireLock() throws KeeperException, InterruptedException {
// 創(chuàng)建鎖節(jié)點
createLock();
// 嘗試獲取鎖
accquireLock();
}
// 創(chuàng)建鎖節(jié)點
public void createLock() throws KeeperException, InterruptedException {
// 1
Stat stat = zooKeeper.exists(LOCK_NODE_PATH, false);
if (stat == null) {
zooKeeper.create(LOCK_NODE_PATH, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
}
// 2 創(chuàng)建臨時有序節(jié)點
lockPath = zooKeeper.create(LOCK_NODE_PATH + "/" + LOCK_NODE_NAME,
new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
}
// 監(jiān)視上一個節(jié)點是否被刪除
Watcher watcher = new Watcher() {
public void process(WatchedEvent event) {
if (event.getType() == Event.EventType.NodeDeleted) {
synchronized (this) {
notifyAll();
}
}
}
};
// 嘗試獲取鎖
public void accquireLock() throws InterruptedException, KeeperException {
// 獲取Locks下的所有子節(jié)點
List<String> list = zooKeeper.getChildren(LOCK_NODE_PATH, false);
Collections.sort(list);
// Locks/Lock_000000001
int index = list.indexOf(lockPath.substring(LOCK_NODE_PATH.length()+1));
if(index == 0) {
System.out.println("拿到鎖");
} else {
// 上一個節(jié)點的路徑
String path = list.get(index -1);
Stat stat = zooKeeper.exists(LOCK_NODE_PATH + "/" + path, watcher);
if (stat == null) {
accquireLock();
} else {
synchronized (watcher) {
watcher.wait();
}
accquireLock();
}
}
}
// shifang suo
public void releaseLock() throws InterruptedException, KeeperException {
zooKeeper.delete(this.lockPath, -1);
zooKeeper.close();
System.out.println("鎖已經(jīng)釋放" + this.lockPath);
}
}
import org.apache.zookeeper.KeeperException;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
/**
* 測試分布式鎖
*/
public class TickSeller {
private void sell() {
System.out.println("sell begin...");
// 線程隨機休眠5000,模擬現(xiàn)實中的費時操作
int mils = 5000;
try {
// 代表復雜邏輯執(zhí)行
Thread.sleep(mils);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("sell end...");
}
public void sellWithLock() throws KeeperException, InterruptedException {
ZkLock lock= new ZkLock();
// 獲取鎖
lock.tryAccquireLock();
sell();
lock.releaseLock();
}
public static void main(String[] args) throws KeeperException, InterruptedException {
TickSeller seller = new TickSeller();
for (int i=0;i<10;i++) {
seller.sellWithLock();
}
}
}