在Eclipse中如何操作zookpeer
生活随笔
收集整理的這篇文章主要介紹了
在Eclipse中如何操作zookpeer
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
導(dǎo)入jar包
jar包下載鏈接代碼解析
package com.itcast.zookpeer.zk;import java.io.IOException; import java.util.List;import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooDefs.Ids; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.Stat; import org.junit.Before; import org.junit.Test;public class SimpleZkClient {private static final String connectString = "weijie1:2181,weijie2:2181,weijie3:2181";private static final int sessionTimeout = 2000;ZooKeeper zkClient = null;public SimpleZkClient() {System.out.println("構(gòu)造方法");}@Beforepublic void init() throws Exception {zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {@Overridepublic void process(WatchedEvent event) {// 收到事件通知后的回調(diào)函數(shù)(應(yīng)該是我們自己的事件處理邏輯)System.out.println(event.getType() + "---" + event.getPath());try {zkClient.getChildren("/", true);} catch (Exception e) {}}});}/*** 數(shù)據(jù)的增刪改查* * @throws InterruptedException* @throws KeeperException*/@Test// 創(chuàng)建數(shù)據(jù)節(jié)點到zk中public void testCreate() throws KeeperException, InterruptedException {// 參數(shù)1:要創(chuàng)建的節(jié)點的路徑 參數(shù)2:節(jié)點大數(shù)據(jù) 參數(shù)3:節(jié)點的權(quán)限 參數(shù)4:節(jié)點的類型String nodeCreated = zkClient.create("/eclipse1", "hellozk".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);//上傳的數(shù)據(jù)可以是任何類型,但都要轉(zhuǎn)成byte[]}//判斷znode是否存在@Test public void testExist() throws Exception{Stat stat = zkClient.exists("/eclipse", false);System.out.println(stat==null?"not exist":"exist");}// 獲取子節(jié)點@Testpublic void getChildren() throws Exception {List<String> children = zkClient.getChildren("/", true);for (String child : children) {System.out.println(child);}Thread.sleep(Long.MAX_VALUE);}//獲取znode的數(shù)據(jù)@Testpublic void getData() throws Exception {byte[] data = zkClient.getData("/eclipse", false, null);System.out.println(new String(data));}//刪除znode@Testpublic void deleteZnode() throws Exception {//參數(shù)2:指定要刪除的版本,-1表示刪除所有版本zkClient.delete("/eclipse", -1);}//刪除znode@Testpublic void setData() throws Exception {zkClient.setData("/app1", "imissyou angelababy".getBytes(), -1);byte[] data = zkClient.getData("/app1", false, null);System.out.println(new String(data));}}總結(jié)
以上是生活随笔為你收集整理的在Eclipse中如何操作zookpeer的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据结构上机测试2-1:单链表操作A
- 下一篇: 算法6:只有五行的Floyd最短路算法