Zookeeper说明
创建节点(znode) 方法:
create:
提供了两套创建节点的方法,同步和异步创建节点方式。
同步方式:
参数1,节点路径《名称) : InodeName (不允许递归创建节点,也就是说在父节点不存在
的情况下,不允许创建子节点)
参数2,节点内容: 要求类型是字节数组(也就是说,不支持序列化方式,如果需要实现序
列化,可使用java相关序列化框架,如Hessian、Kryo框架)
参數3,节点权限: 使用Ids.OPEN_ACL_UNSAFE开放权限即可。(这个参数一般在权展
没有太高要求的场景下,没必要关注)
参数4,节点类型: 创建节点的类型: CreateMode,提供四种首点象型
PERSISTENT(持久节点)
PERSISTENT SEQUENTIAL(持久顺序节点)
EPHEMERAL(临时节点)
EPHEMERAL SEQUENTAL(临时顺序节点)
导入依赖
<dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.6</version> </dependency>
Zookeeper客户端连接
package com.zook.util; import org.apache.zookeeper.*; import org.apache.zookeeper.data.Stat; import java.io.IOException; import java.util.concurrent.CountDownLatch; public class Zookeeper { //集群连接地址 private static final String CONNECT_ADDR="0.0.0.0:2181"; //session超时时间 private static final int SESSION_OUTTIMF=2000; /* public Zookeeper(String connectAddr, int sessionOuttimf, Watcher watcher) { }*/ //信号量,阻塞程序执行,用户等待zookeeper连接成功,发送成功信号 private static final CountDownLatch countDownLath=new CountDownLatch(1); public static void main(String[] args) throws IOException, InterruptedException, KeeperException { ZooKeeper zk=new ZooKeeper(CONNECT_ADDR,SESSION_OUTTIMF,new Watcher(){ @Override public void process(WatchedEvent watchedEvent) { //获取时间的状态 Event.KeeperState keeperState=watchedEvent.getState(); Event.EventType tvenType=watchedEvent.getType(); //如是建立连接 if (Event.KeeperState.SyncConnected==keeperState){ if (Event.EventType.None==tvenType){ //如果建立连接成功,则发送信号量,然后阻塞程序向下执行 countDownLath.countDown(); System.out.println("建立连接!!!"); } } } }); //进行阻塞 countDownLath.await(); //创建父节点 /*String zk01 = zk.create("/zk01", "123".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); System.out.println(zk01);*/ //更改节点 /*Stat stat = zk.setData("/zk01", "123".getBytes(), 0); System.out.println(stat);*/ //获取节点 /*byte[] data = zk.getData("/zk01", false, new Stat()); System.out.println(new String(data,"UTF-8"));*/ //删除 zk.delete("/zk01",-1); //关闭 zk.close(); } }