Java操作Zookeeper很简单,但是前提要把包导对。
关于Zookeeper的Linux环境搭建可以参考我的这篇博客:Linux环境下Zookeeper安装
下面进入正题:
一、导入依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> modelVersion>4.0.0</groupId>cn.zookeeperartifactId>zookeeper_demoversion>0.0.1-SNAPSHOT> <!-- https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper --> dependencies> dependency>org.apache.zookeeper>zookeeper>3.4.6> project>
package zookeeper_demo; import java.util.List; java.util.concurrent.CountDownLatch; org.apache.zookeeper.CreateMode; org.apache.zookeeper.KeeperException; org.apache.zookeeper.WatchedEvent; org.apache.zookeeper.Watcher; org.apache.zookeeper.Watcher.Event.KeeperState; org.apache.zookeeper.ZooDefs.Ids; org.apache.zookeeper.ZooKeeper; org.apache.zookeeper.data.Stat; public class BaseZookeeper implements Watcher{ private ZooKeeper zookeeper; /** * 超时时间 */ private static final int SESSION_TIME_OUT = 2000; private CountDownLatch countDownLatch = new CountDownLatch(1); void process(WatchedEvent event) { if (event.getState() == KeeperState.SyncConnected) { System.out.println("Watch received event"); countDownLatch.countDown(); } } 连接zookeeper * @param host * @throws Exception void connectZookeeper(String host) throws Exception{ zookeeper = new ZooKeeper(host,SESSION_TIME_OUT,this); countDownLatch.await(); System.out.println("zookeeper connection success"); } * 创建节点 * path * data * public String createNode(String path,String data) Exception{ return .zookeeper.create(path,data.getBytes(),Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT); } * 获取路径下所有子节点 * @return * KeeperException * InterruptedException public List<String> getChildren(String path) KeeperException,InterruptedException{ List<String> children = zookeeper.getChildren(path,1)">false); return children; } * 获取节点上面的数据 * path 路径 * public String getData(String path) byte[] data = zookeeper.getData(path,1)">false,1)">nullif (data == ) { return ""; } new String(data); } * 设置节点信息 * data 数据 * public Stat setData(String path,InterruptedException{ Stat stat = zookeeper.setData(path,-1 stat; } * 删除节点 * InterruptedException * KeeperException void deleteNode(String path) InterruptedException,KeeperException{ zookeeper.delete(path,-1 * 获取创建时间 * public String getCTime(String path) String.valueOf(stat.getCtime()); } * 获取某个路径下孩子的数量 * public Integer getChildrenNum(String path) int childenNum = zookeeper.getChildren(path,1)">).size(); childenNum; } * 关闭连接 * void closeConnection() InterruptedException{ if (zookeeper != ) { zookeeper.close(); } } void main(String[] args) Exception { BaseZookeeper zookeeper = BaseZookeeper(); zookeeper.connectZookeeper("192.168.126.128:2181"); List<String> children = zookeeper.getChildren("/"); System.out.println(children); } }
完成以上两步,即可完成Java连接并对Zookeeper的简单操作。
原文链接:/zookeeper/869238.html