zookeeper API介紹java
導入依賴項apache
操做代碼示例 bash
Zookeeper官方爲Java提供了Zookeeper API,可是Zookeeper API並很差用,只須要了解一下便可,之後能夠使用ZkClient(對Zookeeper API作了封裝)。服務器
由於zookeeper依賴的jar包比較多,因此推薦使用Maven來管理以來,只須要在pom.xml的依賴中添加下面的內容便可:session
<dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.14</version> <type>pom</type> </dependency>
package cn.ganlixin.test; import java.io.IOException; import java.util.concurrent.CountDownLatch; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.EventType; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.apache.zookeeper.ZooDefs.Ids; import org.apache.zookeeper.ZooKeeper; public class ZookeeperAPI { public static void main(String[] args) throws IOException, InterruptedException, KeeperException { // 建立一個countDownLatch,用來管理程序運行進度 CountDownLatch countDownLatch = new CountDownLatch(1); // 鏈接串 //String connectString = "127.0.0.1:2181; 127.0.0.1:2182; 127.0.0.1:2183"; // 會話超時時間 int sessionTimeout = 2000; // 建立zookeeper鏈接(是異步鏈接,因此須要讓主線程阻塞,在鏈接成功後,讓主線程繼續執行) ZooKeeper zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() { @Override public void process(WatchedEvent event) { // 事件類型 EventType type = event.getType(); // 時間狀態 KeeperState state = event.getState(); if (state == KeeperState.SyncConnected) { if (type == EventType.None) { System.out.println("成功鏈接Zookeeper服務器"); countDownLatch.countDown(); // 讓主線程繼續運行 } } } }); // 阻塞,等待countDownLatch減爲0便可繼續運行 countDownLatch.await(); // 利用建立的zk鏈接,進行各類操做 zk.create("/test", "hello world".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); byte[] data = zk.getData("/test", null, null); System.out.println(new String(data, 0, data.length)); // 關閉鏈接 zk.close(); } }