Zookeeper客户端java代码操作
上篇博客记录了shell命令操作zookeeper集群的方式,这次尝试采用java代码来操作。通过查阅API,发现并不困难。
1. 首先获得客户端与服务器的连接
//zookeeper客户端 private ZooKeeper zkCli; //连接地址 private static final String CONNECT_STRING = "hadoop102:2181,hadoop103:2181,hadoop104:2181"; //session过期时间 private static final int SESSION_TIMEOUT = 2000; /** * 创建客户端实例对象 * * @throws IOException */ @Before public void before() throws IOException { zkCli = new ZooKeeper(CONNECT_STRING, SESSION_TIMEOUT, (event) -> { System.out.println("默认的回调函数"); }); }
2. 列出根节点下的子节点(非递归)
@Test public void ls() throws KeeperException, InterruptedException { List<String> children = zkCli.getChildren("/", e -> { System.out.println("自定义回调函数"); }); System.out.println("---------------------"); for (String child : children) { System.out.println(child); } System.out.println("+++++++++++++++++++++"); Thread.sleep(Long.MAX_VALUE); }
3. 在一个节点下创建子节点
@Test public void create() throws KeeperException, InterruptedException { //parameter1:创建的节点路径 parameter2:节点的数据 parameter3:节点权限 parameter4:节点类型 String str = zkCli.create("/idea", "idea2019".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); System.out.println(str); Thread.sleep(Long.MAX_VALUE); }
4. 获取指定节点的内容
@Test public void get() throws KeeperException, InterruptedException { byte[] data = zkCli.getData("/simon", true, new Stat()); String str = new String(data); System.out.println(str); }
5. 给指定节点设置值
@Test public void set() throws KeeperException, InterruptedException { Stat stat = zkCli.setData("/simon", "abcd".getBytes(), 1); System.out.println(stat.getDataLength()); }
6. 获取指定节点的状态信息
@Test public void stat() throws KeeperException, InterruptedException { Stat exists = zkCli.exists("/ideaa", false); if (exists == null) { System.out.println("节点不存在"); } else { System.out.println(exists.getDataLength()); } }
7. 删除指定节点
@Test public void delete() throws KeeperException, InterruptedException { Stat exists = zkCli.exists("/idea", false); if (exists != null) { zkCli.delete("/idea", exists.getVersion()); } }
8. 循环注册,动态获取节点的信息。
也就是当节点有任何变化时,就会调用回调函数,动态的显示节点的变化信息。
@Test public void register() throws KeeperException, InterruptedException { byte[] data = zkCli.getData("/simon2", new Watcher() { @Override public void process(WatchedEvent watchedEvent) { try { register();//发生事件,通知的时候在注册一遍,实现了循环调用 } catch (KeeperException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }, null); System.out.println(new String(data)); } @Test public void testRegister() { try { register(); //调用register()方法,将进程卡住,循环执行register Thread.sleep(Long.MAX_VALUE); } catch (Exception e) { e.printStackTrace(); } }
代码很简单易懂,只是有些内部原理还是有些模糊,例如:Stat是什么?zookeeper是怎么监听到节点发生变化的?又是如何将变化通知给客户端的?在之后的博客中将会详细记录。~