1. 程式人生 > >zk筆記--使用java客戶端訪問

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自帶的客戶端檢視:

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

Do it,Insist it,Enjoy it

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