zk筆記--使用java客戶端訪問

 

一:簡介

  zk已經跑起來了,接下來就是怎麼使用它,讓它提供服務,

我使用maven創建工程:依賴如下

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
   
	<dependency>
	  <groupId>org.slf4j</groupId>
	  <artifactId>slf4j-log4j12</artifactId>
	  <version>1.7.0</version>
	</dependency>

	<dependency>
	  <groupId>org.apache.zookeeper</groupId>
	  <artifactId>zookeeper</artifactId>
	  <version>3.3.5</version>
	</dependency>

    注意: 依賴中的zk版本是3.3.5這個版本號和啓動的zkserver的版本號一致,我使用過高版本的依賴,發現不謙容低版本。

二:demo代碼

package com.netboy.netty.zk;

import java.io.IOException;
import java.util.List;

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.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * TODO:   zk客戶端的demo,
 *       實現創建節點,父子節點信息,隨機獲取子節點信息,刪除節點信息功能
 *       
 *    注意: 使用ZK依賴的時候,版本號需要和ZK服務器的版本一樣,不然會出現異常,即版本不兼容。本例使用的是3.3.5版本。
 *    
 *   netboy 2013-3-26下午12:57:35
 */
public class ZkDemo {
	private static final Logger logger = LoggerFactory.getLogger(ZkDemo.class);
	private ZooKeeper zk;
	private String parentDir = "/serverName";
	private String childDir1 = "/127.0.0.1:8081";
	private String childDir2 = "/127.0.0.1:8082";
	private String childDir3 = "/127.0.0.1:8083";

/**
 * 初始化zk連接
 * 
 * @throws IOException
 */
	public void init() throws IOException {

		zk = new ZooKeeper("127.0.0.1:8081,127.0.0.1:8082,127.0.0.1:8083",
				1000 * 60, new Watcher() {
			// 監控所有被觸發的事件
			public void process(WatchedEvent event) {
				logger.info("已經觸發了 {} 事件! ",event.getType());
				//System.out.println("已經觸發了" + event.getType() + "事件!");
			}
		});
	}

/**
 *  從ZK 中獲得節點信息,客戶端隨機獲取父目錄下的子節點目錄,已達到隨機均勻的獲得主機信息
 * 
 */
	public void getDirData() throws InterruptedException, KeeperException {
		int count = 100;

		int b = 0;
		int c = 0;
		int d = 0;

		String parentDir = "/serverName";

		List<String> childDir = zk.getChildren(parentDir, true);
		for(int i = 0; i < count; i++) {
			int temp = i % 3;
			switch(temp) {
			case 0:
				b++;
				break;
			case 1:
				c++;
				break;
			case 2:
				d++;
				break;
			default:
				break;
			}
			logger.info("you get {}th child Node: {} ",
                              new Object[]{temp,childDir.get(temp)});
			Thread.sleep(100);
		}
		logger.info("the b = {} the c ={} the d ={} ",
				                      new Object[]{ b,c,d } );
		String string = new String(zk.getData(parentDir, false, null));

		logger.info("the search node is : {} ", string);
	}

/**
 * 創建父子節點,獲得父子節點內容,及父節點下面的所有子節點目錄名
 * 
 * @throws KeeperException
 * @throws InterruptedException
 */

	public void createData() throws KeeperException, InterruptedException {

		//創建父子節點
		zk.create(parentDir, "test".getBytes(), 
				Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

		zk.create(parentDir + childDir1, null, 
				Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
		zk.create(parentDir + childDir2, null, 
				Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
		zk.create(parentDir + childDir3, null, 
				Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

		List<String> childDir = zk.getChildren(parentDir, true);

		logger.info("the {}  child dir is :{} ", 
				new Object[]{ parentDir,childDir });

		byte[] object = zk.getData(parentDir, false, null);

		if(object != null) {
			String string = new String(object);
			logger.info("you had created an node ,it is :{} ={} ",
					new Object[]{ parentDir,string });
		} else {
			logger.info("the dir: {} is null", parentDir);
		}

	}

/**
 * 刪除創建的父子節點
 * 
 * @throws KeeperException
 * @throws InterruptedException
 */
	public void delete() throws InterruptedException, KeeperException {
		if(zk.exists(parentDir + childDir1, false) != null) {
			zk.delete(parentDir + childDir1, -1);
		}
		if(zk.exists(parentDir + childDir2, false) != null) {
			zk.delete(parentDir + childDir2, -1);
		}
		if(zk.exists(parentDir + childDir3, false) != null) {
			zk.delete(parentDir + childDir3, -1);
		}
		if(zk.exists(parentDir, false) != null) {
			zk.delete(parentDir, -1);
		}

		logger.info("you have deleted the node : {} ", parentDir);
	}

	public static void main(String[] args) throws IOException,
	                         KeeperException, InterruptedException {
		// 創建一個與服務器的連接
		ZkDemo demo = new ZkDemo();
		demo.init();
        //如果創建的節點已經存在,就先刪除
		demo.delete();
		
		demo.createData();
		
		//均勻獲得子目錄節點信息
		demo.getDirData();
		
		//刪除創建的新節點
		demo.delete();
	}
}


     代碼中註釋的比較清晰,這裏就不在介紹了。


三: 運行

  運行 成功會出現如下日誌:




將main函數中的demo.delete();註釋掉。重新運行。

使用zk自帶的客戶端查看:



源碼下載鏈接: ZKclientDemo源碼

*************************************************************************************************************************************

Do it,Insist it,Enjoy it


*************************************************************************************************************************************





發佈了41 篇原創文章 · 獲贊 4 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章