首页 > 代码库 > Zookeeper异常ConnectionLossException解决

Zookeeper异常ConnectionLossException解决

今天安装了CentOS虚拟机,然后写了一个Zookeeper测试程序,这个测试程序连接到运行在本机的Zookeeper服务能够正常运行。

但是当连接到远端的CentOS虚拟机上的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)


不用虚拟机,使用真实服务器也一样有这个异常,换成Windows server 2008服务器也有这个异常,看起来好像访问本机Zookeeper服务就可以,但是访问远端就不行。


上网一查,全是说什么到Zookeeper服务的连接未完成,说是加下面这段代码就好了:

CountDownLatch connectedLatch = new CountDownLatch(1);
        if (States.CONNECTING == zk.getState()) {  
            try {  
                connectedLatch.await();  
            } catch (InterruptedException e) {  
                throw new IllegalStateException(e);  
            }  
        }


我觉得这有点扯淡,首先官网没有任何提到要加这样的代码来等待连接准备好的话语,其次为什么本机可以,远端就不行,难道天生本机就一定能够快速建立好连接,远端就要等一等么?

于是我决定自己思考,想了一天才觉得可能是防火墙问题,于是把windwos server 2008防火墙关闭,OK了,把CentOS防火墙关闭,也OK了,哎!


CentOS关闭防火墙命令:

CentOS Linux开启和关闭防火墙命令有两种,一种是临时的,重启即复原;另外一种是永久性的,重启不会复原。
1) 临时生效,重启后复原
开启: service iptables start
关闭: service iptables stop
2) 永久性生效,重启后不会复原
开启: chkconfig iptables on
关闭: chkconfig iptables off

我执行的是永久修改的命令,执行完了也可以不重启电脑,重启防火墙服务即可: service iptables restart


附上我的测试程序:

package com.jiq.test;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
 
public class ZooKeeperTest {
 
    public static void main(String[] args) throws Exception{
        ZooKeeper zk = new ZooKeeper("192.168.1.108:2181", 3000, null);
        System.out.println("=========创建节点===========");
        if(zk.exists("/test", false) == null)
        {
        	zk.create("/test", "znode1".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }
        System.out.println("=============查看节点是否安装成功===============");
        System.out.println(new String(zk.getData("/test", false, null)));
        
        System.out.println("=========修改节点的数据==========");
        zk.setData("/test", "zNode2".getBytes(), -1);
        System.out.println("========查看修改的节点是否成功=========");
        System.out.println(new String(zk.getData("/test", false, null)));
        
        System.out.println("=======删除节点==========");
        zk.delete("/test", -1);
        System.out.println("==========查看节点是否被删除============");
        System.out.println("节点状态:" + zk.exists("/test", false));
        zk.close();
    } 
}


运行结果:

=========创建节点===========
=============查看节点是否安装成功===============
znode1
=========修改节点的数据==========
========查看修改的节点是否成功=========
zNode2
=======删除节点==========
==========查看节点是否被删除============
节点状态:null



Zookeeper异常ConnectionLossException解决