【前言】zookeeper應(yīng)用的場(chǎng)景主要有四種:通知服務(wù)、配置管理、集群管理、分布式鎖。其還有一最大的特點(diǎn)就是數(shù)據(jù)同步。zookeeper任何一個(gè)節(jié)點(diǎn)上的數(shù)據(jù)都可以同步到其他ZK節(jié)點(diǎn)上。
業(yè)務(wù)需求,將服務(wù)器信息日志存儲(chǔ)到zookeeper集群上,通過(guò)java操作zookeeper獲取日志信息來(lái)展現(xiàn)并分析。
【準(zhǔn)備】
zookeeper-3.4.5.tar.gz
【1】
開啟zookeeper服務(wù)

【2】
創(chuàng)建java工程,添加jar包(jar可以解壓tar.gz包,在lib中獲?。?/p>

【3】
代碼編寫
ZK.java
import java.util.concurrent.CountDownLatch;
import org.apache.log4j.Logger;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
public class ZK implements Watcher {
private static Logger log = Logger.getLogger(ZK.class);
// 緩存時(shí)間
private static final int SESSION_TIME = 2000;
protected ZooKeeper zookeeper;
protected CountDownLatch countDownLatch = new CountDownLatch(1);
// 鏈接zk集群
public void connect(String hosts) throws Exception {
zookeeper = new ZooKeeper(hosts, SESSION_TIME, this);
countDownLatch.await();
}
@Override
public void process(WatchedEvent event) {
// TODO Auto-generated method stub
if (event.getState() == KeeperState.SyncConnected) {
countDownLatch.countDown();
}
}
// 關(guān)閉集群
public void close() throws InterruptedException {
zookeeper.close();
}
}
ZKOperator.java
import java.util.Arrays;
import java.util.List;
import org.apache.log4j.Logger;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
public class ZKOperator extends ZK {
private static Logger logger = Logger.getLogger(ZKOperator.class);
/**
*
* <b>function:</b>創(chuàng)建持久態(tài)的znode,比支持多層創(chuàng)建.比如在創(chuàng)建/parent/child的情況下,無(wú)/parent.無(wú)法通過(guò)
*
* @author lvfang
* @createDate 2017-01-10 17:22:22
* @param path
* @param data
* @throws KeeperException
* @throws InterruptedException
*/
public void create(String path, byte[] data) throws KeeperException,
InterruptedException {
/**
* 此處采用的是CreateMode是PERSISTENT 表示The znode will not be automatically
*/
this.zookeeper.create(path, data, Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
}
/**
*
* <b>function:</b>獲取節(jié)點(diǎn)信息
*
* @author lvfang
* @createDate 2017-01-10 17:22:22
* @param path
* @throws KeeperException
* @throws InterruptedException
*/
public void getChild(String path) throws KeeperException,
InterruptedException {
try {
List<String> list = this.zookeeper.getChildren(path, false);
if (list.isEmpty()) {
logger.debug(path + "中沒(méi)有節(jié)點(diǎn)");
} else {
logger.debug(path + "中存在節(jié)點(diǎn)");
for (String child : list) {
logger.debug("節(jié)點(diǎn)為:" + child);
}
}
} catch (KeeperException.NoNodeException e) {
// TODO: handle exception
throw e;
}
}
public byte[] getData(String path) throws KeeperException,
InterruptedException {
return this.zookeeper.getData(path, false, null);
}
public static void main(String[] args) {
try {
ZKOperator zkoperator = new ZKOperator();
zkoperator.connect("192.168.1.201");
byte[] data = new byte[] { 'a', 'b', 'c', 'd' };
//創(chuàng)建root目錄,此root目錄是創(chuàng)建在zookeeper中zoo.cfg配置中的path下
zkoperator.create("/root", null);
System.out.println(Arrays.toString(zkoperator.getData("/root")));
//root下創(chuàng)建child1目錄,并寫入內(nèi)容
zkoperator.create("/root/child1", data);
System.out.println(Arrays.toString(zkoperator
.getData("/root/child1")));
zkoperator.create("/root/child2", data);
System.out.println(Arrays.toString(zkoperator
.getData("/root/child2")));
//root下創(chuàng)建child3目錄,并寫入內(nèi)容
String zktest = "ZooKeeper的Java API測(cè)試";
zkoperator.create("/root/child3", zktest.getBytes());
logger.debug("獲取設(shè)置的信息:"
+ new String(zkoperator.getData("/root/child3")));
//獲取集群中的子節(jié)點(diǎn)信息
System.out.println("節(jié)點(diǎn)孩子信息:");
zkoperator.getChild("/root");
//關(guān)閉zk
zkoperator.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

2017-01-10_172433.png
單個(gè)java文件完成zookeeper操作
import java.util.concurrent.CountDownLatch;
import org.apache.log4j.Logger;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
public class TestZK implements Watcher {
private static Logger logger = Logger.getLogger(ZKOperator.class);
protected CountDownLatch countDownLatch = new CountDownLatch(1);
@Override
public void process(WatchedEvent event) {
// TODO Auto-generated method stub
if (event.getState() == KeeperState.SyncConnected) {
countDownLatch.countDown();
}
}
public static void main(String[] args) throws Exception {
// 創(chuàng)建一個(gè)與服務(wù)器的連接 需要(服務(wù)端的 ip+端口號(hào))(session過(guò)期時(shí)間)(Watcher監(jiān)聽(tīng)注冊(cè))
ZooKeeper zk = new ZooKeeper("192.168.1.201", 3000, new Watcher() {
// 監(jiān)控所有被觸發(fā)的事件
public void process(WatchedEvent event) {
// TODO Auto-generated method stub
System.out.println("已經(jīng)觸發(fā)了" + event.getType() + "事件!");
}
});
// 創(chuàng)建一個(gè)目錄節(jié)點(diǎn)
/**
* CreateMode: PERSISTENT (持續(xù)的,相對(duì)于EPHEMERAL,不會(huì)隨著client的斷開而消失)
* PERSISTENT_SEQUENTIAL(持久的且?guī)ы樞虻模?EPHEMERAL (短暫的,生命周期依賴于client session)
* EPHEMERAL_SEQUENTIAL (短暫的,帶順序的)
*/
zk.create("/testRootPath", "testRootData".getBytes(),
Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// 創(chuàng)建一個(gè)子目錄節(jié)點(diǎn)
zk.create("/testRootPath/testChildPathOne",
"testChildDataOne".getBytes(), Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
System.out
.println(new String(zk.getData("/testRootPath", false, null)));
// 取出子目錄節(jié)點(diǎn)列表
System.out.println(zk.getChildren("/testRootPath", true));
// 創(chuàng)建另外一個(gè)子目錄節(jié)點(diǎn)
zk.create("/testRootPath/testChildPathTwo",
"testChildDataTwo".getBytes(), Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
System.out.println(zk.getChildren("/testRootPath", true));
// 修改子目錄節(jié)點(diǎn)數(shù)據(jù)
zk.setData("/testRootPath/testChildPathOne", "hahahahaha".getBytes(),
-1);
byte[] datas = zk.getData("/testRootPath/testChildPathOne", true, null);
String str = new String(datas, "utf-8");
System.out.println(str);
// 刪除整個(gè)子目錄 -1代表version版本號(hào),-1是刪除所有版本
zk.delete("/testRootPath/testChildPathOne", -1);
System.out.println(zk.getChildren("/testRootPath", true));
System.out.println(str);
}
}
其他API方法
/**
* create(): 發(fā)起一個(gè)create操作. 可以組合其他方法 (比如mode 或background) 最后以forPath()方法結(jié)尾
delete(): 發(fā)起一個(gè)刪除操作. 可以組合其他方法(version 或background) 最后以forPath()方法結(jié)尾
checkExists(): 發(fā)起一個(gè)檢查ZNode 是否存在的操作. 可以組合其他方法(watch 或background) 最后以forPath()方法結(jié)尾
getData(): 發(fā)起一個(gè)獲取ZNode數(shù)據(jù)的操作. 可以組合其他方法(watch, background 或get stat) 最后以forPath()方法結(jié)尾
setData(): 發(fā)起一個(gè)設(shè)置ZNode數(shù)據(jù)的操作. 可以組合其他方法(version 或background) 最后以forPath()方法結(jié)尾
getChildren(): 發(fā)起一個(gè)獲取ZNode子節(jié)點(diǎn)的操作. 可以組合其他方法(watch, background 或get stat) 最后以forPath()方法結(jié)尾
inTransaction(): 發(fā)起一個(gè)ZooKeeper事務(wù). 可以組合create, setData, check, 和/或delete 為一個(gè)操作, 然后commit() 提交
*/