创建Zookeeper客户端及遇到的问题
作者:互联网
创建Zookeeper客户端
1.代码
package com.itguigu.zk;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.apache.zookeeper.*;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
public class zkClient {
// 注意:逗号前后不能有空格
private static String connectString = "node1:2181,node2:2181,node3:2181";
private static int sessionTimeout = 10000;
private ZooKeeper zkClient;
@Before
public void init() throws IOException {
//选中sessionTimeout alt+enter 选择Create fields...
//ctrl + alt + f 将zkclient升级为全局变量
zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent event) {
System.out.println("------------------------");
List<String> children = null;
try {
children = zkClient.getChildren("/", true); //process执行到这里开启新的监听,并执行后面程序,有变化再执行process
for (String child : children) {
System.out.println(child);
}
System.out.println("----------------");
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
// 创建子节点
@Test
public void create() throws KeeperException, InterruptedException {
// 参数 1:要创建的节点的路径; 参数 2:节点数据 ; 参数 3:节点权限 ;参数 4:节点的类型
String nodeCreated = zkClient.create("/atguigu", "ss.avi".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
@Test
public void getChildren() throws KeeperException, InterruptedException {
List<String> children = zkClient.getChildren("/", true); //这里注册监听,监听到就执行new Watcher()中的process,会输出System.out.println("------------------------"); 开启新的监听
for (String child : children) {
System.out.println(child);
}
//延时阻塞
//Thread.sleep(Long.MAX_VALUE);
Thread.sleep(20000);
}
@Test
public void exists() throws KeeperException, InterruptedException {
Stat stat = zkClient.exists("/atguigu", false);
System.out.println(stat==null?"not exist":"exist");
}
}
2.创建过程快捷键
2.1 new Zookeeper
new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent event) {
}
}).var
2.2 选中sessionTimeout 用alt+enter组合 选择Create field … 定义全局变量注意加static
2.3 ctrl + alt + f 将zkclient升级为全局变量
2.4 alt+enter 抛异常
3.遇到问题
解决方案:
问题存在于private static final int sessionTimeout = 2000 中设置的sessionTimeout值太小,将这个值增大,改为5000,问题解决。
解释:sessionTimeout是会话超时时间,也就是当一个zookeeper超过该时间没有心跳,则认为该节点故障。所以,如果此值小于zookeeper的创建时间,则当zookeeper还未来得及创建连接,会话时间已到,因此抛出异常认为该节点故障。
标签:创建,void,Zookeeper,println,sessionTimeout,zkClient,new,public,客户端 来源: https://blog.csdn.net/qq_44141629/article/details/121441012