2018-08-22 18:02:25.0|分类: zookeeper|浏览量: 1193
创建zookeeper import java.io.IOException; import java.util.concurrent.CountDownLatch; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; public class ZookeeperDemo { private static final String CONNECTION_STRING="127.0.0.1:2182"; private static final int SESSION_TIMEOUT = 5000; private static CountDownLatch latch = new CountDownLatch(1); public static void main(String[] args) throws IOException, InterruptedException { ZooKeeper zk = new ZooKeeper(CONNECTION_STRING, SESSION_TIMEOUT, new Watcher(){ @Override public void process(WatchedEvent event) { if(event.getState() == Event.KeeperState.SyncConnected){ latch.countDown(); } } }); 建立zookeeper会话的过程是异步的,当构造完zk对象后,线程将继续执行后续代码,但此时会话可能尚未建立完毕,所以要用CountDownLatch 工具。 latch.await(); System.out.println(zk); } } 构造函数public ZooKeeper(String connectString, int sessionTimeout, Watcher watcher)
connectString:连接服务器列表(ip+端口号),如果多个地址用“,”分割,例如:"127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002"。 sessionTimeout:心跳检测时间周期,单位毫秒。 watcher:监视器接口,事件处理通知器。
同步获取节点集合 public List<String> getChildren(final String path, Watcher watcher) List<String> listNode = zk.getChildren("/", null); for (String node : listNode) { System.out.println(node); } //异步获取节点集合 public void getChildren(final String path, Watcher watcher, ChildrenCallback cb, Object ctx) zk.getChildren("/", null, new ChildrenCallback() { @Override public void processResult(int rc, String path, Object ctx, List<String> children) { System.out.println( "path="+path); for (String node : children) { System.out.println(node); } } }, null); exit()判断节点是否存在 public Stat exists(final String path, Watcher watcher) throws KeeperException, InterruptedException Stat stat = zk.exists("/root", null); System.out.println(stat); stat = zk.exists("/root2", null); System.out.println(stat); 打印信息如下: 4294967298,4294967300,1534486665805,1534486780890,1,0,0,0,11,0,4294967298 null exit()异步判断节点是否存在 public void exists(final String path, Watcher watcher, StatCallback cb, Object ctx) 创建节点create public String create(final String path, byte data[], List<ACL> acl, CreateMode createMode) CreateMode类型分为4种 1.PERSISTENT--持久型 2.PERSISTENT_SEQUENTIAL--持久顺序型 3.EPHEMERAL--临时型 4.EPHEMERAL_SEQUENTIAL--临时顺序型 zk.create("/root/city", "beijing".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); 获取节点数据getData public byte[] getData(final String path, Watcher watcher, Stat stat) throws KeeperException, InterruptedException 设置节点数据setData public Stat setData(final String path, byte data[], int version) throws KeeperException, InterruptedException 删除节点delete public void delete(final String path, int version) throws InterruptedException, KeeperException |