zookeeper是一个分布式服务管理工具,本身具备高可用性,很多知名分布式系统入hadoop、Hbase等都采用zk管理。
常见的两个应用场景:1、服务的注册与发现 2、集群统一配置
下面看一下使用java 对zk进行交互的常用api
首先maven引入:
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.5.3-beta</version>
</dependency>
<dependency>
<groupId>com.github.sgroschupf</groupId>
<artifactId>zkclient</artifactId>
<version>0.1</version>
</dependency>
import org.I0Itec.zkclient.ZkClient; import org.I0Itec.zkclient.serialize.SerializableSerializer; import org.apache.zookeeper.CreateMode; /** * @author panteng * @description * @date 17-5-24. */ public class Zk { public static void main(String[] arges) { String ZKServers = "10.38.164.80:2181,10.38.164.80:2182,10.38.164.80:2183"; /** * 创建会话 * new SerializableSerializer() 创建序列化器接口,用来序列化和反序列化 */ ZkClient zkClient = new ZkClient(ZKServers, 10000, 10000, new SerializableSerializer()); System.out.println("conneted ok!"); //订阅节点的子节点变化 zkClient.subscribeChildChanges("/javaApp", new ZKChildListener()); String appPath = zkClient.create("/javaApp/api", "javaApp", CreateMode.EPHEMERAL_SEQUENTIAL); //输出创建节点的路径 System.out.println("created path:" + appPath); //订阅数据的变化 zkClient.subscribeDataChanges(appPath, new ZkDataListener()); //读数据 String str = zkClient.readData(appPath); System.out.println(str); //写数据 zkClient.writeData(appPath, "newJavaApp"); System.out.println(zkClient.readData(appPath)); //判断节点是否存在 System.out.println(zkClient.exists("/javaApp/api0000000010")); try { Thread.sleep(20000); } catch (Exception e) { } } }
import org.I0Itec.zkclient.IZkDataListener; /** * @author panteng * @description * @date 17-5-24. */ public class ZkDataListener implements IZkDataListener { /** * 节点数据发生变化时 触发此函数 * * @param s 发生变化的节点路径 * @param o 节点变化后的数据 * @throws Exception */ @Override public void handleDataChange(String s, Object o) throws Exception { System.out.println("Change = " + s + " obj=" + o); } @Override public void handleDataDeleted(String s) throws Exception { System.out.println("Delete = " + s); } }
import org.I0Itec.zkclient.IZkDataListener; /** * @author panteng * @description * @date 17-5-24. */ public class ZkDataListener implements IZkDataListener { /** * 节点数据发生变化时 触发此函数 * * @param s 发生变化的节点路径 * @param o 节点变化后的数据 * @throws Exception */ @Override public void handleDataChange(String s, Object o) throws Exception { System.out.println("Change = " + s + " obj=" + o); } @Override public void handleDataDeleted(String s) throws Exception { System.out.println("Delete = " + s); } }
遍历所有节点
public static void getAllNodes(ZkClient zkClient, String currentPath) { try { List<String> stringList = zkClient.getChildren(currentPath); for (String str : stringList) { if ("/".equals(currentPath)) { str = currentPath + str; } else { str = currentPath + "/" + str; } System.out.println(str); getAllNodes(zkClient, str); } } catch (Exception e) { if (e.getMessage().indexOf("KeeperErrorCode = NoNode for") > -1) { return; } } }