Zookeeper异常ConnectionLossException解决

时间:2023-01-06 17:53:45

项目中要求做一个将配置文件读取到zookeeper节点上的工具:

开发代码如下:

Zookeeper异常ConnectionLossException解决

Zookeeper异常ConnectionLossException解决

Zookeeper异常ConnectionLossException解决

但是当连接到远端的Zookeeper服务之后,出现了下面异常:

Exception in thread "main" org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /test
at org.apache.zookeeper.KeeperException.create(KeeperException.Java:99)
at org.apache.zookeeper.KeeperException.create(KeeperException.java:51)
at org.apache.zookeeper.ZooKeeper.exists(ZooKeeper.java:1501)
at org.apache.zookeeper.ZooKeeper.exists(ZooKeeper.java:1529)
at com.jiq.test.ZooKeeperTest.main(ZooKeeperTest.java:12)

原因:

new出ZooKeeper实例时只是建立了与服务端之间的会话,此时TCP连接可能还未建立完成,如果这时发出ZooKeeper操作命令的确会出现连接丢失异常,虽然这种概率相对较小。

当客户端与服务端连接建立之后客户端会收到一个SyncConnected事件,此时将connectedSemaphore减到零就可以让阻塞的主线程继续运行,再来发出ZooKeeper操作命令就不会出现连接丢失的异常了。

解决方法:

将上图中注释的代码放出来就可以啦!