java 學習筆記(四) java連接ZooKeeper
public class Demo2 {
public static void main(String[] args) { String connectString = "192.168.168.133:2181"; int sessionTimeout = 500000; // 會話時間。設置長一點,如果不夠長,則會connect loss try { // 建立zookeeper鏈接 ZooKeeper zk = new ZooKeeper(connectString, sessionTimeout, new Watcher(){ public void process(WatchedEvent event) { // 監控所有觸發的事件 System.out.println("start do something"); EventType type = event.getType(); // 事件類型。枚舉 KeeperState state = event.getState(); // 狀態。 枚舉
// type.getIntValue();
switch (type) {
case None: // int值對應 -1
System.out.println("none 事件觸發");
break;
case NodeCreated: // int值對應 1
System.out.println("創建節點事件發生了");
break;
case NodeDeleted: // int值對應 2
System.out.println("刪除節點事件發生了");
break;
case NodeDataChanged: // int值對應 3
System.out.println("節點數據改變事件發生了");
break;
case NodeChildrenChanged: // int值對應 4
System.out.println("子節點改變事件發生了");
break;
default:
System.out.println("I do not know what operate you do");
break;
}
// state.getIntValue(); NoSyncConnected 1和Unknown-1
switch (state) {
case Disconnected: // 0
System.out.println("失去連接");
break;
case SyncConnected: // 3
System.out.println("異步鏈接");
break;
case Expired: // -112
System.out.println("超時過期");
break;
default:
break;
}
System.out.println("end"); } }); System.out.println("zk創建成功"); List<String> list = zk.getChildren("/", true); // 獲取所有節點 if(list != null) { for(String s : list) System.out.println(s); } // 在/app5節點下創建child節點 zk.create("/app7", "/app8的子節點數據".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); // 會對數據持久化,服務下次啟動任然存在 zk.create("/app8", "/app8的子節點數據".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, new StringCallback(){ public void processResult(int rc, String path, Object ctx, String name) { System.out.println("rc: " + rc); System.out.println("path: " + path); System.out.println("Object:" + ctx); System.out.println("name: " + name); } }, "ctx object"); } catch (IOException e) { e.printStackTrace(); } catch (KeeperException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }
}
zk每一次操縱都會被監控watcher記錄下來
出現這種報錯是由於創建節點的時候沒有創建父節點 /app1
java 學習筆記(四) java連接ZooKeeper