zookeeper學習筆記--刪除節點
阿新 • • 發佈:2018-11-20
1:刪除節點API
同步方式 |
public void delete(final String path, int version) |
非同步方式 |
public void delete(final String path, int version, voidCallback cb, Object ctx) |
- 必須先刪除葉子節點,才能再刪除根節點
2:引數說明
path |
指定資料節點的節點路徑 |
version |
指定節點的資料版本,即表明本次刪除操作是針對該資料版本進行的,-1代表任何版本 |
cb |
註冊一個非同步回撥函式 |
ctx |
用於傳遞上下文資訊的物件 |
3:程式碼樣例
package LearningZK; import java.util.concurrent.CountDownLatch; import org.apache.zookeeper.*; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.apache.zookeeper.ZooDefs.Ids; public class UsingZookeeperAPI implements Watcher{ private static CountDownLatch connectedSemaphore = new CountDownLatch(1); public static void main(String[] args) throws Exception{ /*使用ZK構造方法例項化ZK物件來建立會話*/ /*new UsingZookeeperAPI 實現watcher介面,重寫process方法,處理服務端返回的非同步通知*/ ZooKeeper zookeeper = new ZooKeeper("172.21.10.136:2181", 5000, new UsingZookeeperAPI()); System.out.println(zookeeper.getState()); // long sessionID = zookeeper.getSessionId(); //獲取會話ID // byte[] sessionPasswd = zookeeper.getSessionPasswd(); //獲取會話金鑰 try { connectedSemaphore.await(); } catch (InterruptedException e) {} System.out.println("ZooKeeper session established."); /*以同步的方式建立ZK臨時節點*/ String path1 = zookeeper.create("/ZK_test", "".getBytes(),Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); System.out.println("Create Znode Success:"+path1); /*以同步的方式建立ZK臨時順序節點*/ String path2 = zookeeper.create("/ZK_test","".getBytes(),Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL); System.out.println("Create Znode Succsess:"+path2); /*以非同步的方式建立ZK臨時節點*/ zookeeper.create("/ZK_test_async", "".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, new AsyncCallBack(), "I am content"); /*以同步的方式刪除ZK節點*/ zookeeper.delete("/ZK_test", -1); //-1表示任何版本 System.out.println("Delete Znode Success"); /*以非同步的方式刪除ZK節點*/ //zookeeper.delete("/ZK_test",-1,new IsCallback(),"content"); Thread.sleep(Integer.MAX_VALUE); } /*處理ZK服務端watcher通知,再接收到服務端發來的SyncConnected通知後,解除主程式的等待阻塞*/ public void process(WatchedEvent event) { System.out.println("Receive watched event:" + event); if (KeeperState.SyncConnected == event.getState()) { connectedSemaphore.countDown(); } } } /*非同步建立節點回調方法簡單實現*/ class AsyncCallBack implements AsyncCallback.StringCallback{ public void processResult(int rc, String path, Object ctx, String name){ System.out.println("Create path result:["+rc+","+path+","+ctx+",real path name"+name); } } /*非同步刪除節點回調方法簡單實現*/ class IsCallback implements AsyncCallback.VoidCallback{ public void processResult(int rc, String path, Object ctx){ System.out.println("rc:"+rc+"path:"+path+"Object:"+ctx); } }