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"));
}
});
}
}