zookeeper JavaAPI入門操作

1 安裝

zookeeper 是支持window安裝的,下載安裝包,解壓之後,只需要在conf目錄下面創建zoo.cfg文件即可,單機環境下配置如下:

# The number of milliseconds of each tick
tickTime=2000
# The number of ticks that the initial 
# synchronization phase can take
initLimit=10
# The number of ticks that can pass between 
# sending a request and getting an acknowledgement
syncLimit=5
# the directory where the snapshot is stored.
dataDir=/tmp/zookeeper
# the port at which the clients will connect
clientPort=2181

2 啓動Server

zkServer.cmd start

3 啓動client

zkCli.cmd -server localhost:2181

4 使用Java API 與zookeeper 服務端交互


在pom.xml文件中加入依賴

        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.3.0</version>
            <exclusions>
                <exclusion>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                </exclusion>
            </exclusions>
        </dependency>


public class demo {
    //會話超時時間,設置爲與系統默認時間一致
    private static final int SESSION_TIMEOUT = 30000;

    //創建ZooKeeper實例
    ZooKeeper zk;

    //創建Watcher實例
    Watcher wh = new Watcher() {
        public void process(org.apache.zookeeper.WatchedEvent event) {
            System.out.println(event.toString());
        }
    };

    //初始化ZooKeeper實例
    private void createZKInstance() throws IOException {
        zk = new ZooKeeper("localhost:2181", demo.SESSION_TIMEOUT, this.wh);

    }

    private void ZKOperations() throws IOException, InterruptedException, KeeperException {
        System.out.println("\n1.創建ZooKeeper節點(znode:zoo2,數據:myData2,權限:OPEN_ACL_UNSAFE,節點類型:Persistent");
        zk.create("/zoo2", "myData2".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

        System.out.println("\n2.查看是否創建成功:");
        System.out.println(new String(zk.getData("/zoo2", false, null)));

        System.out.println("\n3.修改節點數據");
        zk.setData("/zoo2", "shenlan211314".getBytes(), -1);

        System.out.println("\n4.查看是否修改成功:");
        System.out.println(new String(zk.getData("/zoo2", false, null)));

        System.out.println("\n5.刪除節點");
        zk.delete("/zoo2", -1);

        System.out.println("\n6.查看節點是否被刪除:");
        System.out.println("節點狀態:[" + zk.exists("/zoo2", false) + "]");
    }

    private void ZKClose() throws InterruptedException {
        zk.close();
    }

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        demo dm = new demo();
        dm.createZKInstance();
        dm.ZKOperations();
        dm.ZKClose();
    }
}

5 應用程序實例:創建組,加入組,列出組成員,刪除組


創建zookeeper實例

public class ZooKeeperInstance {
    //會話超時時間,設置爲與系統默認時間一致
 	public static final int SESSION_TIMEOUT=30000;
 
	//創建ZooKeeper實例
	ZooKeeper zk;
	
	//創建Watcher實例
	Watcher wh=new Watcher(){
		public void process(WatchedEvent event){
			System.out.println(event.toString());
		}
	};
	
 //初始化Zookeeper實例
	public void createZKInstance() throws IOException{	
		zk=new ZooKeeper("10.100.90.183:2181",ZooKeeperInstance.SESSION_TIMEOUT,this.wh);
	}
	
	//關閉ZK實例
	public void ZKclose() throws InterruptedException{
		zk.close();
	}
}


創建組

public class CreateGroup extends ZooKeeperInstance {

    //創建組
    //參數:groupPath
    public void createPNode(String groupPath) throws KeeperException, InterruptedException{
        //創建組
        String cGroupPath=zk.create(groupPath, "group".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        //輸出組路徑
        System.out.println("創建的組路徑爲:"+cGroupPath);
    }

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException{
        CreateGroup cg=new CreateGroup();
        cg.createZKInstance();
        cg.createPNode("/ZKGroup");
        cg.ZKclose();
    }


}


加入組

public class JoinGroup extends ZooKeeperInstance {
    //加入組操作
	public int Join(String groupPath,int k) throws KeeperException, InterruptedException{
		String child=k+"";
		child="child_"+child;
		
		//創建的路徑
		String path=groupPath+"/"+child;
		//檢查組是否存在
		if(zk.exists(groupPath,true) != null){
			//如果存在,加入組
			zk.create(path,child.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
			return 1;
		}
		else{
			System.out.println("組不存在!");
			return 0;
		}
	}
	
	//加入組操作
	public void MultiJoin() throws KeeperException, InterruptedException{
		for(int i=0;i<10;i++){
			int k=Join("/ZKGroup",i);
			//如果組不存在則退出
			if(0==k)
				System.exit(1);
		}
	}
	
	public static void main(String[] args) throws IOException, KeeperException, InterruptedException{
		JoinGroup jg=new JoinGroup();
		jg.createZKInstance();
		jg.MultiJoin();
		jg.ZKclose();
	}	
}


列出成員

public class ListMembers extends ZooKeeperInstance {
    public void list(String groupPath) throws KeeperException, InterruptedException{
		//獲取所有子節點
		List<String> children=zk.getChildren(groupPath, false);
		if(children.isEmpty()){
			System.out.println("組"+groupPath+"中沒有組成員存在!");
			System.exit(1);
		}
		for(String child:children)
			System.out.println(child);		
	}
	
	public static void main(String[] args) throws IOException, KeeperException, InterruptedException{
		ListMembers lm=new ListMembers();
		lm.createZKInstance();
		lm.list("/ZKGroup");
	}
}


刪除組

public class CreateGroup extends ZooKeeperInstance {

    //創建組
    //參數:groupPath
    public void createPNode(String groupPath) throws KeeperException, InterruptedException{
        //創建組
        String cGroupPath=zk.create(groupPath, "group".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        //輸出組路徑
        System.out.println("創建的組路徑爲:"+cGroupPath);
    }

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException{
        CreateGroup cg=new CreateGroup();
        cg.createZKInstance();
        cg.createPNode("/ZKGroup");
        cg.ZKclose();
    }


}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章