以下是Linux下Zookeeper API使用指南:
安装Zookeeper,可从官网下载二进制包,按官方文档安装。添加Java依赖,若用Maven,在pom.xml
中添加<dependency><groupId>org.apache.zookeeper</groupId><artifactId>zookeeper</artifactId><version>3.7.0</version></dependency>
。
ZooKeeper
类,构造函数为ZooKeeper(String connectionString, int sessionTimeout, Watcher watcher)
,如ZooKeeper zk = new ZooKeeper("localhost:2181", 3000, new Watcher() {...});
。create
方法,有多种重载形式,如zk.create("/path", "data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
。getData
方法,有同步和异步版本,如byte[] data = zk.getData("/path", false, null);
。setData
方法,需指定版本号,如zk.setData("/path", "newData".getBytes(), stat.getVersion());
。delete
方法,要指定版本号,如zk.delete("/path", stat.getVersion());
。Watcher
接口实现,如zk.exists("/path", new Watcher() {...});
。可使用getChildren
获取子节点列表,getACL
和setACL
获取和设置访问控制列表,sync
方法用于同步客户端视图与ZooKeeper。对于批量操作,可使用multi
方法。