package com.cn.zookeeper;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.Test;
import java.io.IOException;
/**
* zookeeper增删改查操作
* */
public class ZKCrud {
//zookeeper连接字符串
private static final String CONNECT_STRING="hadMaster01:2181,hadMaster02:2181,hadSlave01:2181,hadSlave02:2181,hadSlave03:2181";
//设置超时时间
private static final int SESSION_TIMEOUT=50000;
//获取zookeeper连接,没有配置监听,最后一个参数设置为null
static ZooKeeper zk=null;
static{
try {
zk=new ZooKeeper(CONNECT_STRING,SESSION_TIMEOUT,null);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 创建一个节点
* */
@Test
public void createNode() throws KeeperException, InterruptedException, IOException {
String createNode=zk.create("/cc","this is cc Node".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
System.out.println(createNode);
}
/**
* 判断节点是否存在
* */
@Test
public void existsNode() throws KeeperException, InterruptedException {
Stat isExist=zk.exists("/cc0000000007",null);
if(isExist==null){
System.out.println("节点不存在");
}else{
System.out.println("节点存在");
}
}
/**
* 查看节点的数据
* */
@Test
public void selectNodeData() throws KeeperException, InterruptedException {
byte[] nodeData=zk.getData("/cc0000000007",false,null);
System.out.println(new String(nodeData));
}
/**
* 修改节点的数据
* */
@Test
public void updateNodeData() throws KeeperException, InterruptedException {
Stat setData=zk.setData("/cc0000000007","update cc node".getBytes(),-1);
if(setData == null){
System.out.println("节点不存在,修改不成功");
}else{
System.out.println("节点存在,修改成功");
}
}
/**
* 删除节点
* */
@Test
public void deleteNodeData() throws KeeperException, InterruptedException {
zk.delete("/cc0000000007",-1);
}
/**
* 关闭zookeeper的连接
* */
@Test
public void closeZK() throws InterruptedException {
zk.close();
}
}