zookeeper JAVA API

김하영·2021년 6월 17일
0
post-custom-banner

zookeeper JAVA API을 이용한 znode 생성 / 읽기 / 삭제 및 쓰기

ZooKeeper 클라이언트 라이브러리는 자바와 C의 두 가지 언어로 제공됩니다.
다음 섹션에서는 JAVA 바인딩에 대해 설명합니다.

JAVA 바인딩

zookeeper Java 바인딩을 구성하는 패키지는 org.apache.zookeeper 와 org.apache.zookeeper.data 두 가지 입니다.

zookeeper 를 구성하는 나머지 패키지는 내부적으로 사용되거나 서버 구현의 일부입니다.
org.apache.zookeeper.data 패키지는 컨테이너로 간단하게 사용되는 생성 된 클래스로 구성되어 있습니다.

zookeeper Java 클라이언트가 사용하는 기본 클래스는 zookeeper 클래스입니다.

zookeeper 앙상블을 연결하는 옵션을 제공하며 다음과 같은 방법이 있습니다.

  1. connect − connect to the zookeeper host

  2. create − create a znode

  3. exists − check wahcher a znode exists and its information

  4. getData − get data from a particular znode

  5. setData − set data in a particular znode

  6. getChildren − get all sub-nodes available in a particular znode

  7. delete − get a particular znode and all its children

  8. connect − connect to the zookeeper host

- 생성자

zookeeper 클래스는 생성자를 통해 연결 기능을 제공합니다.
생성자의 서명은 다음과 같습니다.

ZooKeeper(String host, int sessionTimeout, Watcher watcher)

  1. host : zookeeper server host

  2. sessionTimeout:session timeout in milliseconds

  3. watcher:a watcher object which will be notified of state changes, may also be notified for node events

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
 
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
 
public class ZooKeeperConnection {
   private ZooKeeper zk;
   final CountDownLatch connectedSignal = new CountDownLatch(1);
 
   public ZooKeeper connect(String host) throws IOException, InterruptedException {
      zk = new ZooKeeper(host, 5000, new Watcher() {
         @Override
         public void process(WatchedEvent event) {
            if (event.getState() == Event.KeeperState.SyncConnected) {
               connectedSignal.countDown();
            }
         }
      });
      connectedSignal.await();
      return zk;
   }
 
   public void close() throws InterruptedException {
      zk.close();
   }

- create : create a znode
create 메소드의 서명은 다음과 같습니다.

create(String path, byte[] data, List acl, CreateMode createMode)

  1. path – the path for the node
  2. data – the initial data for the node
  3. acl – the acl for the node
  4. createMode – specifying whether the node to be created is ephemeral and/or sequential
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
 
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;
import org.apache.zookeeper.ZooKeeper;
 
public class ZkCreate {
   private static ZooKeeper zk;
 
   final static CountDownLatch connectedSignal = new CountDownLatch(1);
 
   public static void create(String path, byte[] data) throws KeeperException, InterruptedException {
      zk.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
   }
 
   public static ZooKeeper connect(String host) throws IOException, InterruptedException {
      zk = new ZooKeeper(host, 5000, new Watcher() {
         @Override
         public void process(WatchedEvent event) {
            if (event.getState() == Event.KeeperState.SyncConnected) {
               connectedSignal.countDown();
            }
         }
      });
      connectedSignal.await();
      return zk;
   }
 
   public static void close() throws InterruptedException {
      zk.close();
   }
 
   public static void main(String[] args) {
      String path = "/znode";
      byte[] data = "my_data".getBytes();
         
      try {
            zk = connect("localhost");
            create(path, data);
            close();
      } catch (Exception e) {
         System.out.println(e.getMessage());
      }
   }

exists : check wahcher a znode exists and its information
exists 메소드 의 서명은 다음과 같습니다.

exists(String path, boolean watch)

  1. path – the node path
  2. watch – whether need to watch this node

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class ZkExists {
   private static ZooKeeper zk;

   final static CountDownLatch connectedSignal = new CountDownLatch(1);

   public static Stat znode_exists(String path) throws KeeperException, InterruptedException {
      return zk.exists(path, true);
   }

   public static ZooKeeper connect(String host) throws IOException, InterruptedException {
      zk = new ZooKeeper(host, 5000, new Watcher() {
         @Override
         public void process(WatchedEvent event) {
            if (event.getState() == Event.KeeperState.SyncConnected) {
               connectedSignal.countDown();
            }
         }
      });
      connectedSignal.await();
      return zk;
   }

   public static void close() throws InterruptedException {
      zk.close();
   }

   public static void main(String[] args) {
      String path = "/znode";

      try {
         zk = connect("localhost");
         Stat stat = znode_exists(path);
         if (stat != null) {
            System.out.println("Node exists " + stat.toString());
         } else {
            System.out.println("Node does not exists");
         }
         close();
      } catch (Exception e) {
         System.out.println(e.getMessage());
      }
   }
}

getData : get data from a particular znode
getData 메소드 의 서명은 다음과 같습니다.

getData(String path, boolean watch, Stat stat)

  1. path – the given path
  2. watch – whether need to watch this node
  3. stat – the stat of the node
import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class ZkGetData {
   private static ZooKeeper zk;

   final static CountDownLatch connectedSignal = new CountDownLatch(1);

   public static Stat znode_exists(String path) throws KeeperException, InterruptedException {
      return zk.exists(path, true);
   }

   public static ZooKeeper connect(String host) throws IOException, InterruptedException {
      zk = new ZooKeeper(host, 5000, new Watcher() {
         @Override
         public void process(WatchedEvent event) {
            if (event.getState() == Event.KeeperState.SyncConnected) {
               connectedSignal.countDown();
            }
         }
      });
      connectedSignal.await();
      return zk;
   }

   public static void close() throws InterruptedException {
      zk.close();
   }

   public static void main(String[] args) {
      String path = "/znode";

      try {
         zk = connect("localhost");
         Stat stat = znode_exists(path);
         if (stat != null) {
            byte[] dataByte = zk.getData(path, false, null);
            String pathData = new String(dataByte, "UTF-8");
            System.out.println("node : " + path + " , data : " + pathData);
            
         } else {
            System.out.println("Node does not exists");
         }
         close();
      } catch (Exception e) {
         System.out.println(e.getMessage());
      }
   }
}

setData : set data in a particular znode
setData 메소드 의 서명은 다음과 같습니다.

setData(String path, byte[] data, int version)

  1. path – the path of the node
  2. data – the data to set
  3. version – the expected matching version

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class ZkSetData {
   private static ZooKeeper zk;

   final static CountDownLatch connectedSignal = new CountDownLatch(1);

   public static Stat znode_exists(String path) throws KeeperException, InterruptedException {
      return zk.exists(path, true);
   }

   public static ZooKeeper connect(String host) throws IOException, InterruptedException {
      zk = new ZooKeeper(host, 5000, new Watcher() {
         @Override
         public void process(WatchedEvent event) {
            if (event.getState() == Event.KeeperState.SyncConnected) {
               connectedSignal.countDown();
            }
         }
      });
      connectedSignal.await();
      return zk;
   }

   public static void close() throws InterruptedException {
      zk.close();
   }

   public static void main(String[] args) {
      String path = "/znode";
      byte[] data = "updateData".getBytes();
      try {
         zk = connect("localhost");
         Stat stat = znode_exists(path);
         zk.setData(path, data, stat.getVersion());
         close();
      } catch (Exception e) {
         System.out.println(e.getMessage());
      }
   }
}

getChildren : get all sub-nodes available in a particular znode

getChildren(String path, boolean watch)

  1. path – the given path
  2. watch – whether need to watch this node
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class ZkGetChildren {
   private static ZooKeeper zk;

   final static CountDownLatch connectedSignal = new CountDownLatch(1);

   public static Stat znode_exists(String path) throws KeeperException, InterruptedException {
      return zk.exists(path, true);
   }

   public static ZooKeeper connect(String host) throws IOException, InterruptedException {
      zk = new ZooKeeper(host, 5000, new Watcher() {
         @Override
         public void process(WatchedEvent event) {
            if (event.getState() == Event.KeeperState.SyncConnected) {
               connectedSignal.countDown();
            }
         }
      });
      connectedSignal.await();
      return zk;
   }

   public static void close() throws InterruptedException {
      zk.close();
   }

   public static void main(String[] args) {
      String path = "/znode";

      try {
         zk = connect("localhost");
         Stat stat = znode_exists(path);
         if (stat != null) {
            List <String> rootChilds = zk.getChildren(path, false);
            if(rootChilds.size() > 0){
                  for(int i = 0; i < rootChilds.size(); i++){
                  	System.out.println(rootChilds.get(i));
                  }
            }
         } else {
            System.out.println("Node does not exists");
         }
         close();
      } catch (Exception e) {
         System.out.println(e.getMessage());
      }
   }
}

delete : delete the node with the given path.

delete(String path, int version)

  1. path – the path of the node
  2. version – the expected matching version
import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

public class ZkDelete {
   private static ZooKeeper zk;

   final static CountDownLatch connectedSignal = new CountDownLatch(1);

   public static ZooKeeper connect(String host) throws IOException, InterruptedException {
      zk = new ZooKeeper(host, 5000, new Watcher() {
         @Override
         public void process(WatchedEvent event) {
            if (event.getState() == Event.KeeperState.SyncConnected) {
               connectedSignal.countDown();
            }
         }
      });
      connectedSignal.await();
      return zk;
   }

   public static void close() throws InterruptedException {
      zk.close();
   }

   public static void main(String[] args) {
      String path = "/znode";
      try {
         zk = connect("localhost");
         zk.delete(path, zk.exists(path, true).getVersion());
         close();
      } catch (Exception e) {
         System.out.println(e.getMessage());
      }
   }
}
profile
Back-end Developer
post-custom-banner

0개의 댓글