zookeeper zkclient API小案例

来源:互联网 发布:sleep water 知乎 编辑:程序博客网 时间:2024/05/16 12:05
public class ZkClientBase {


//zookeeper地址
static final String CONNECT_ADDR = "112.124.121.34:2181";
//session超时时间
static final int SESSION_OUTTIME = 5000;

public static void main(String[] args) throws Exception {
ZkClient zkc = new ZkClient(new ZkConnection(CONNECT_ADDR),5000);

// zkc.createEphemeral("/temp");
// zkc.createPersistent("/super/c1",true);

// zkc.deleteRecursive("/super");


// zkc.createPersistent("/super","1234");
// zkc.createPersistent("/super/c1","c1内容");
// zkc.createPersistent("/super/c2","c2内容");
//
// List<String> list = zkc.getChildren("/super");
//
// for(String p:list){
// System.out.println(p);
// String rp = "/super/"+p;
// String data = zkc.readData(rp);
// System.out.println("节点为:"+rp+",内容为:"+data);
// }

zkc.writeData("/super/c1", "新内容");
System.out.println(zkc.readData("/super/c1"));
System.out.println(zkc.exists("/super/c1"));

Thread.sleep(10000);

}


}


public class ZkClientWatcher1 {
//zookeeper地址
static final String CONNECT_ADDR = "112.124.121.34:2181";
//session超时时间
static final int SESSION_OUTTIME = 5000;

public static void main(String[] args) throws Exception {
ZkClient zkc = new ZkClient(new ZkConnection(CONNECT_ADDR),5000);

//对父节点添加监听子节点变化
zkc.subscribeChildChanges("/super", new IZkChildListener() {
@Override
public void handleChildChange(String parentPath, List<String> currentChilds)
throws Exception {
System.out.println("parentPath: " + parentPath);
System.out.println("currentChilds: " + currentChilds);
}
});

Thread.sleep(3000);

zkc.createPersistent("/super");
Thread.sleep(1000);

zkc.createPersistent("/super" + "/" + "c1", "c1内容");
Thread.sleep(1000);

zkc.createPersistent("/super" + "/" + "c2", "c2内容");
Thread.sleep(1000);

zkc.delete("/super/c2");
Thread.sleep(1000);

//zkc.deleteRecursive("/super");
Thread.sleep(Integer.MAX_VALUE);
}
}


public class ZkClientWatcher2 {
//zookeeper地址
static final String CONNECT_ADDR = "112.124.121.34:2181";
//session超时时间
static final int SESSION_OUTTIME = 5000;

public static void main(String[] args) throws Exception {
ZkClient zkc = new ZkClient(new ZkConnection(CONNECT_ADDR),5000);
zkc.createPersistent("/super", "1234");
//对父节点添加监听子节点变化
zkc.subscribeDataChanges("/super",new IZkDataListener() {

@Override
public void handleDataDeleted(String path) throws Exception {
System.out.println("删除的节点为:" + path);

}

@Override
public void handleDataChange(String path, Object data) throws Exception {
System.out.println("变更的节点为:" + path + ", 变更内容为:" + data);

}
});

Thread.sleep(3000);
zkc.writeData("/super", "456", -1);
Thread.sleep(1000);


zkc.delete("/super");
Thread.sleep(Integer.MAX_VALUE);
}
}

原创粉丝点击