zookeeper基本操作

基本操作,create,update,delete

 public static void main(String[] args) throws Exception {
    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();

    CuratorFramework curatorFramework = builder.connectString(CONNECTION_STR).
            sessionTimeoutMs(5000).
            retryPolicy(new ExponentialBackoffRetry(100, 3)).build();

    curatorFramework.start();
    createNode(curatorFramework);
//    updateNode(curatorFramework);
//    deleteNode(curatorFramework);
  }

   /**创建**/
  private static void createNode(CuratorFramework curatorFramework) throws Exception {
      curatorFramework.create().creatingParentContainersIfNeeded()
          .withMode(CreateMode.PERSISTENT).forPath("/data/program","test".getBytes());
  }
  /**更新*/
   private static void updateNode(CuratorFramework curatorFramework) throws Exception {
    curatorFramework.setData().forPath("/data/program","aaa".getBytes());
  }
  /*删除*/
  private static void deleteNode(CuratorFramework curatorFramework)  throws Exception {
    Stat stat=new Stat();
    final String s = new String(curatorFramework.getData().storingStatIn(stat).forPath("/data/program"));
    curatorFramework.delete().withVersion(stat.getVersion()).forPath("/data/program");
  }

Watch

public static void main(String[] args) throws Exception {
   CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
   CuratorFramework curatorFramework = builder.connectString(CONNECTION_STR).sessionTimeoutMs(5000).retryPolicy(new ExponentialBackoffRetry(100, 3)).build();
   curatorFramework.start();
   addListenerWithChild(curatorFramework);
   System.in.read();
 }

  private static void addListenerWithNode(CuratorFramework curatorFramework) throws Exception {
   NodeCache nodeCache =new NodeCache(curatorFramework,"/watch",false);
   NodeCacheListener nodeCacheListener= () ->{
     System.out.println("receive Node Changed");
     System.out.println(nodeCache.getCurrentData().getPath()+"---"+new String(nodeCache.getCurrentData().getData()));
   };
   nodeCache.getListenable().addListener(nodeCacheListener);
   nodeCache.start();
 }


文章作者: 凌云
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 凌云 !
  目录