package com.fun.zkdemo;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import java.io.IOException;
/**
* @author fun
* Date: 2017/9/1 下午2:55
*/
public class ZKTest implements Watcher {
public static final int SESSION_TIMEOUT = 2000;
ZooKeeper zk;
public static void main(String[] args) {
ZKTest zkTest = new ZKTest("127.0.0.1:2181",SESSION_TIMEOUT);
String testData = zkTest.getData("/test_node");
System.out.println(testData);
zkTest.setData("/test_node","hello zookeeper");
}
public ZKTest(String connString,int sessionTimeout) { // 創(chuàng)建鏈接
try {
zk = new ZooKeeper(connString, sessionTimeout, this);
} catch (IOException e) {
e.printStackTrace();
}
}
public String getData(String path) { // 讀取數(shù)據(jù)
byte[] data = new byte[0];
try {
data = this.zk.getData(path,this,null); // 讀取數(shù)據(jù)并設(shè)置watch
System.out.println("session id=" + zk.getSessionId());
} catch (Exception e) {
e.printStackTrace();
}
return new String(data);
}
public void setData(String path,String data) { // 設(shè)置數(shù)據(jù)
try {
Stat stat = this.zk.exists(path,null);
this.zk.setData(path,data.getBytes(),stat.getVersion());
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void process(WatchedEvent event) { // watch事件觸發(fā)的時(shí)候執(zhí)行
System.out.println("keeperState=" + event.getState().getIntValue());
System.out.println("EventType=" + event.getState().getIntValue());
}
}
示例中,先去讀數(shù)據(jù)撩鹿,并設(shè)置了watch谦炬,之后在修改數(shù)據(jù),就觸發(fā)了process方法节沦。會(huì)執(zhí)行process里面的代碼