pom依賴
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.9</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>4.0.1</version>
</dependency>
組件
- curator-framework:對zookeeper的底層api的一些封裝
- curator-client:提供一些客戶端的操作,例如重試策略等
- curator-recipes:封裝了一些高級特性,如:Cache事件監聽、選舉、分佈式鎖、分佈式計數器、分佈式Barrier等
基本操作
- create() 創建節點
- getData() 獲取節點
- getChildren() 獲取子節點信息
- NodeCache 註冊監聽 監聽節點值變更(重複監聽)
- PathChildrenCache 註冊子節點監聽(重複監聽)
- TreeCache 註冊監聽,監聽節點及子節點的變更 (重複監聽)
package com.zzhijian.zookeeperdemo.zk;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.CuratorZookeeperClient;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.api.CuratorListener;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.*;
import java.util.List;
@Slf4j
public class CuratorApiDemo {
private static String ZK_ADDRESS = "zkServer:2181,zkServer:2182,zkServer:2183";
private static Integer SESSION_TIME_OUT_MS = 1000*10;
private static Integer CONNECTION_TIME_OUT_MS = 1000*10*6;
private static ZooKeeper zooKeeper;
private static CuratorFramework curatorFramework;
public static void main(String[] args) throws Exception{
init();
getNodeChildCuratorListener();
watchNodeCache();
watchChildNodeCache();
watchTreeNodeCache();
Thread.sleep(1000* 60*10);
}
public static void initClient() throws Exception{
CuratorZookeeperClient curatorZookeeperClient = new CuratorZookeeperClient(ZK_ADDRESS, SESSION_TIME_OUT_MS, CONNECTION_TIME_OUT_MS, new Watcher() {
@Override
public void process(WatchedEvent event) {
log.error("事件被觸發了 --- 連接狀態:{},事件:{} ---, 在這裏我們可以做一些事情!!!",event.getState(),event.getType());
}
},new RetryNTimes(3,1000));
curatorZookeeperClient.start();
zooKeeper = curatorZookeeperClient.getZooKeeper();
}
public static void createNode() throws Exception{
zooKeeper.create("/curator-02", "node".getBytes(), ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
zooKeeper.create("/curator-02/01", "node".getBytes(), ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
}
public static void init(){
curatorFramework = CuratorFrameworkFactory.builder()
.connectString(ZK_ADDRESS)
.connectionTimeoutMs(CONNECTION_TIME_OUT_MS)
.sessionTimeoutMs(SESSION_TIME_OUT_MS)
.retryPolicy(new RetryNTimes(3,1000))
.build();
curatorFramework.start();
}
public static void createNode01(){
try {
curatorFramework.create()
.forPath("/curator06/0601");
curatorFramework.create()
.creatingParentsIfNeeded()
.withMode(CreateMode.EPHEMERAL)
.withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
.forPath("/curator07/curator0701"," 測試遞歸節點內容".getBytes());
} catch (Exception e) {
e.printStackTrace();
}
}
public static void getNodeValue() {
try {
log.error(new String(curatorFramework.getData().forPath("/curator0601")));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void getNodeChildren() throws Exception{
List<String> list = curatorFramework
.getChildren()
.usingWatcher(new CuratorWatcher() {
@Override
public void process(WatchedEvent watchedEvent) {
log.error("節點列表事件觸發了 --- 連接狀態:{},事件:{} ---, 在這裏我們可以做一些事情!!!",watchedEvent.getState(),watchedEvent.getType());
}
})
.forPath("/curator06");
log.error(list.toString());
}
public static void setNodeValue() {
try {
log.error(String.valueOf(curatorFramework
.setData()
.forPath("/curator07","修改節點信息".getBytes())));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void getNodeChildCuratorListener() throws Exception{
CuratorListener listener = new CuratorListener() {
@Override
public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception {
System.out.println("監聽事件觸發,event內容爲:" + event);
}
};
curatorFramework.getCuratorListenable().addListener(listener);
curatorFramework
.getChildren()
.inBackground()
.forPath("/curator06");
}
public static void watchNodeCache() throws Exception{
NodeCache nodeCache = new NodeCache(curatorFramework,"/curator06");
nodeCache.start();
if(nodeCache.getCurrentData() != null){
log.error("節點的初始化數據爲:"+new String(nodeCache.getCurrentData().getData()));
}else{
log.error("節點初始化數據爲空。。。");
}
nodeCache.getListenable().addListener(new NodeCacheListener() {
@Override
public void nodeChanged() throws Exception {
String data = new String(nodeCache.getCurrentData().getData());
log.error("watchNodeCache-監聽節點變更---{}",data);
}
});
}
public static void watchChildNodeCache() throws Exception{
PathChildrenCache pathChildrenCache = new PathChildrenCache(curatorFramework,"/curator06",true);
pathChildrenCache.start();
pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
@Override
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
log.error("watchChildNodeCache-監聽節點變更---{}",pathChildrenCache.getCurrentData());
}
});
}
public static void watchTreeNodeCache() throws Exception{
TreeCache treeCache = new TreeCache(curatorFramework,"/curator06");
treeCache.start();
treeCache.getListenable().addListener(new TreeCacheListener() {
@Override
public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
log.error("watchTreeNodeCache-監聽節點變更---{},{}",treeCache.getCurrentChildren("/curator06"),treeCache.getCurrentData("/curator06"));
}
});
}
}