1. 程式人生 > >zookeeper簡單客戶端API

zookeeper簡單客戶端API


public class ZKclient{
	public static void main(String[] args){
		private String connectString="ip1:2181,ip2:2181,ip3:2181";
		private int sessionTimeout = 3000;

		ZooKeeper zkCli = null;

		//初始化客戶端
		public void init() throws IOException {
			zkCli = new ZooKeeper(connectString,sessionTimeout,new Watcher(){
				//回撥監聽
				@Override
				public void process(WatchedEvent event){
					System.out.println(event.getPath() + "\t" + event.getState() + "\t" + event.getType());

					try{
						list<String> children = zkCli.getChildren("/",true);
						for(String child : children){
							System.out.println(child);
						}
					} catch(KeeperException e ){
						e.printStackTrace();
					} catch(InterruptException e) {
						e.printStackTrace();
					}
					
				}
			});
		}

		//建立子節點
		public void createZnode() throws KeeperException, InterruptException {
			//第三個引數為應答方式,第四個為節點型別-s/-e
			String path = zkCli.create("/bbq", "shaokao".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSIENTENT);

			System.out.println(path);
		}

		//獲取子節點
		public void getChild() throws KeeperException, InterruptException {
			list<String> children = zkCli.getChildren("/", true);
			for(String child : children){
				System.out.println(child);
			}
			Thread.sleep(Long.MAX_VALUE);//永久監聽
		}

		//刪除節點
		public void rmChildren() throws KeeperException, InterruptException {
			//byte[] data = zkCli.getData("/bbq", true, null);
			//不能刪除節點中的資料,不能存在空節點

			zkCli.delete("/bbq", -1);//-1是刪除所有版本
		}

		//修改資料
		public void setData() throws KeeperException, InterruptException {
			zkCli.setData("/terry", "17".getBytes(), -1);
		}

		//判斷節點是否存在
		public void testExist() throws KeeperException, InterruptException {
			Stat exists = zkCli.exists("/terry", true);
			System.out.println(exists == null ? "not exists" : "exists");
		}
	}
}