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

 angel青彤雪 发布于 2022-11-07 07:09

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

2 个回答
  • 怎么不好好看文档呢
    》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吗,自己检测连接也是逗

    2022-11-12 01:42 回答
  • 找到一个办法,由于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();
                    }
                }
            }
    
    2022-11-12 01:42 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有