package os.zk.demo;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.hadoop.ha.protocolPB.ZKFCProtocolClientSideTranslatorPB;
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.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;
public class SimpleZkClient {
private ZooKeeper zkCli = null;
@Before
public void init() throws IOException {
zkCli = new ZooKeeper("os-1:2181,os-2:2181,os-3:2181", 2000, new Watcher() {
@Override
public void process(WatchedEvent event) {
// TODO Auto-generated method stub
System.out.println("节点:"+event.getPath()+"发生了事件"+event.getType());
}
});
}
/*
* 在zookeeper中创建znode节点(临时/永久)
*/
@Test
public void create() throws UnsupportedEncodingException, KeeperException, InterruptedException {
//PERSISTENT永久节点
String node1 = zkCli.create("/book", "读书".getBytes("utf-8"),Ids.OPEN_ACL_UNSAFE ,CreateMode.PERSISTENT);
//临时节点EPHEMERAL
String node2 = zkCli.create("/library", "图书馆".getBytes("utf-8"),Ids.OPEN_ACL_UNSAFE ,CreateMode.EPHEMERAL);
System.out.println("创建了一个永久节点:"+node1);
System.out.println("创建了一个临时节点:"+node2);
}
/*
* 活动znode节点数据
*/
public void getData() throws KeeperException, InterruptedException, UnsupportedEncodingException {
byte[] data = zkCli.getData("/book", true,null );
System.out.println(new String(data,"utf-8"));
}
/*
* 修改节点数据
*/
@Test
public void testModifyNodeData() throws UnsupportedEncodingException, KeeperException, InterruptedException {
// 修改数据时的版本号用 -1表示所有版本
Stat setData = zkCli.setData("/book", "美女".getBytes("utf-8"), -1);
byte [] data = zkCli.getData("/book", true, null);
System.out.println("修改之后的值为:"+new String(data,"utf-8"));
}
/*
* 删除数据节点
*/
@Test
public void testDelZnode() throws InterruptedException, KeeperException {
Stat exists = zkCli.exists("/book", true);
if(exists!=null) {
zkCli.delete("/book", -1);
}
}
public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
ZooKeeper zkCli = new ZooKeeper("os-1:2181,os-2:2181,os-3:2181", 2000, new Watcher() {
@Override
public void process(WatchedEvent event) {
System.out.println("节点:"+event.getPath()+"发生了事件;" + event.getState());
}
});
//获取 "/"根节点下的字节列表,并对"/"节点注册监听器
List<String> children = zkCli.getChildren("/", true);
for(String child:children) {
System.out.println(child);
}
}
}
zookeeper基本操作
最新推荐文章于 2024-01-25 01:55:47 发布