首页 > java客户端连接zookeeper集群时如何才能避开失效的服务器

java客户端连接zookeeper集群时如何才能避开失效的服务器

集群模式下,比如我有3个zookeeper服务器,分别是zk1,zk2,zk3 ,zookeeper兑现创建时连接串写法是zk1:2181,zk2:2181,zk3:2181 ,按照zk的选举算法,只要有超过半数的节点活着集群就能工作。但是如果这时客户端刚开始初始化,但是zk1挂了,会使用zk1的服务器配置去创建连接,从而报连接被拒绝的异常以致启动退出。这里有什么优雅的方法能在启动阶段让zookeeper自动避开已经失效的节点去选择有效的节点去连接么?


怎么不好好看文档呢
》To create a client session the application code must provide a connection string containing a comma separated list of host:port pairs, each corresponding to a ZooKeeper server (e.g. "127.0.0.1:4545" or "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002"). The ZooKeeper client library will pick an arbitrary server and try to connect to it. If this connection fails, or if the client becomes disconnected from the server for any reason, the client will automatically try the next server in the list, until a connection is (re-)established.

另外你知道zk有个玩意叫watcher吗,自己检测连接也是逗


找到一个办法,由于zk的连接是异步创建的,可以在zookeeper对象new之后等待一下,同时判断state是否为connected,上代码:

if(!zk.getState().equals(States.CONNECTED)){
            while(true){
                if(zk.getState().equals(States.CONNECTED)){
                    break;
                }
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
【热门文章】
【热门文章】