- 先看连接zk代码
private int sessionTimeout = 2000;
public void init() throws IOException {
ZooKeeper zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
//...
}
});
String nodeCreated = zkClient.create("/zkTest", "zkTest.avi".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
- 先说原因
连接客户端的超时时间(SessionTimeout)起码要大于原来zookeeper服务端设置的延迟时间(tickTime*initLimit)
- 首先要回顾一下zookeeper的配置文件conf/zoo.cfg文件中的参数(节选文件部分)
# The number of milliseconds of each tick
tickTime=2000
# The number of ticks that the initial
# synchronization phase can take
initLimit=10
# The number of ticks that can pass between
# sending a request and getting an acknowledgement
syncLimit=5
tickTime:通信心跳时间,ZooKeeper服务器与客户端心跳时间(单位:毫秒)
initLimit:初次通信时限,LF(Leader,Follower)初始连接时能容忍的最多心跳数(tickTime的个数)
syncLimit:同步通信时限,LF通信时间超过syncLimit*tickTime,L认为F已死亡,并从服务器列表中删除F
因为此处tickTime为2000,initLimit为10,因此LF初次连接时的超时时间应起码大于延迟时间tickTime*initLimit的值否则会因为超时而连接失败。
- 所以此处我们只需要将sessionTimeout时间设置大于20000即可解决