zookeeper的JAVA API使用
1.创建连接
2.创建节点
3.监听信息
Watcher.class
4.获取节点
Stat stat = new Stat();
zk.getData(Path,true,stat);
5.修改节点数据
-1表示忽略版本
zk.setData("/test1", "testok".getBytes(), -1);
6.删除节点
可以删除多级目录
zk.setData("/test1", "testok".getBytes(), -1)
完整代码如下
package zookeeper; import org.apache.zookeeper.*; import org.apache.zookeeper.data.Stat; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.Arrays; public class Demo1 { //创建连接 ZooKeeper zk = null; @Before public void connect() { try { zk = new ZooKeeper( "master:2181,node1:2181,node2:2181", 8000, null); } catch (IOException e) { e.printStackTrace(); } } @Test //创建永久性节点 public void creat1(){ try { zk.create("/test1","testone".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT); } catch (KeeperException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } @Test //创建临时节点,会话断开或sessionTimeout时间过期会消失 public void creat2() { try { zk.create("/test2", "testtwo".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); //可以通过加死循环阻塞 } catch (KeeperException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } @Test public void watch(){ try { zk.getChildren("/test2", new Watcher() { public void process(WatchedEvent watchedEvent) { System.out.println("节点挂了"); System.out.println(watchedEvent); //使用Watcher类中的枚举 } }); } catch (KeeperException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } //监听一直运行 while (true){ } } @Test public void getnode(){ try { byte[] data = zk.getData("/test1", true, new Stat()); System.out.println(Arrays.toString(data)); //输出结果 [116, 101, 115, 116, 111, 110, 101] } catch (KeeperException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } @Test public void setnode(){ try { //-1表示忽略版本 zk.setData("/test1", "testok".getBytes(), -1); } catch (KeeperException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }
Zookeeper简介:
Zookeeper集群中节点个数一般为奇数个(>=3),若集群中Master挂掉,剩余节点个数在半数以上时,就可以推举新的主节点,继续对外提供服务。
Zookeeper默认对外提供服务的端口号为2181
Zookeeper集群内部3个节点之间通信默认使用2888:3888