zookeeper基本操作
启动zookeeper zkServer.sh start 进入命令行模式 zkCli.sh zookeeper基本操作 create /gz 01 创建节点 get /gz 查看节点 stat /gz 查看状态 create /gz/dashuju "wangkunhua" 创建子节点 crcreate -e /gz/sahngxi 40 创建临时节点-e(退出去进来的话节点将不会存在了) create -s /gz/java 20 创建有序节点-s delect /gz/dsj 删除节点 可能会有延迟 rmr /gz 递归删除新版本是 deleteall /gz
代码实现增删改查监听
package g4.cn;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
public class CRUDDemo {
private static final String CONN_STR="hadoop1:2181";
@Test
//创建数据
public void testCreate(){
try {
ZooKeeper zk = new ZooKeeper(CONN_STR,5000,null);
zk.create("/x", "123".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.close();
}catch (IOException e){
e.printStackTrace();
}catch (KeeperException e){
e.printStackTrace();
}catch (InterruptedException e){
e.printStackTrace();
}
}
@Test
// 修改数据
public void testSet(){
try {
ZooKeeper zk = new ZooKeeper(CONN_STR,5000,null);
//-1代表任意版本号
zk.setData("/x", "333".getBytes(), -1);
zk.close();
}catch (IOException e){
e.printStackTrace();
}catch (KeeperException e){
e.printStackTrace();
}catch (InterruptedException e){
e.printStackTrace();
}
}
@Test
// 查看数据
public void testGet(){
try {
ZooKeeper zk = new ZooKeeper(CONN_STR,5000,null);
Stat stat = new Stat();
byte[] data = zk.getData("/x",null, stat);
System.out.println(new String(data));
System.out.println(stat.getVersion());
zk.close();
}catch (IOException e){
e.printStackTrace();
}catch (KeeperException e){
e.printStackTrace();
}catch (InterruptedException e){
e.printStackTrace();
}
}
@Test
// 删除数据
public void testDelete(){
try {
ZooKeeper zk = new ZooKeeper(CONN_STR,5000,null);
zk.delete("/x", -1);
zk.close();
}catch (IOException e){
e.printStackTrace();
}catch (KeeperException e){
e.printStackTrace();
}catch (InterruptedException e){
e.printStackTrace();
}
}
@Test
// 监听数据(触发一次)
//服务端输入 set /x "234" 触发回调
public void testWatch01(){
try {
ZooKeeper zk = new ZooKeeper(CONN_STR,5000,null);
Stat stat = new Stat();
byte[] data = zk.getData("/x", new Watcher(){
@Override
public void process(WatchedEvent event){
System.out.println("被回调了01--------");
}}, stat);
System.out.println(new String(data));
System.out.println(stat.getVersion());
Thread.sleep(Long.MAX_VALUE);
}catch (IOException e){
e.printStackTrace();
}catch (KeeperException e){
e.printStackTrace();
}catch (InterruptedException e){
e.printStackTrace();
}
}
@Test
// 监听数据
public void testWatch02(){
try {
ZooKeeper zk = new ZooKeeper(CONN_STR,5000, new Watcher(){
@Override
public void process(WatchedEvent event){
System.out.println("被回调了02--------");
}});
List<String> children = zk.getChildren("/x", true);
for (String node :children){
System.out.println(node);
}
Thread.sleep(Long.MAX_VALUE);
}catch (IOException e){
e.printStackTrace();
}catch (KeeperException e){
e.printStackTrace();
}catch (InterruptedException e){
e.printStackTrace();
}
}
}