安装完成zookeeper后,用Java代码连接阿里云上zookeeper,报出如下错误

2018-04-09 14:11:56,122 [myid:1] - INFO  [solang/*.*.*.*:3887:QuorumCnxManager$Listener@739] - My election bind port: solang/*.*.*.*:3887 2018-04-09 14:11:56,123 [myid:1] - ERROR [solang/*.*.*.*:3887:QuorumCnxManager$Listener@763] - Exception while listening java.net.BindException: Cannot assign requested address (Bind failed) at java.net.PlainSocketImpl.socketBind(Native Method) at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:387) at java.net.ServerSocket.bind(ServerSocket.java:375) at java.net.ServerSocket.bind(ServerSocket.java:329) at org.apache.zookeeper.server.quorum.QuorumCnxManager$Listener.run(QuorumCnxManager.java:742) 2018-04-09 14:11:57,123 [myid:1] - INFO [solang/*.*.*.*:3887:QuorumCnxManager$Listener@776] - Leaving listener 2018-04-09 14:11:57,124 [myid:1] - ERROR [solang/*.*.*.*:3887:QuorumCnxManager$Listener@778] - As I'm leaving the listener thread, I won't be able to participate in leader election any longer: solang/*.*.*.*:3887 2018-04-09 14:11:59,140 [myid:1] - WARN [WorkerSender[myid=1]:QuorumCnxManager@588] - Cannot open channel to 2 at election address solang/*.*.*.*:3888 java.net.SocketTimeoutException: connect timed out at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:589) at org.apache.zookeeper.server.quorum.QuorumCnxManager.connectOne(QuorumCnxManager.java:562) at org.apache.zookeeper.server.quorum.QuorumCnxManager.toSend(QuorumCnxManager.java:538) at org.apache.zookeeper.server.quorum.FastLeaderElection$Messenger$WorkerSender.process(FastLeaderElection.java:452) at org.apache.zookeeper.server.quorum.FastLeaderElection$Messenger$WorkerSender.run(FastLeaderElection.java:433) at java.lang.Thread.run(Thread.java:748) 

参考了很多博客才解决,现在把可能的原因做一下记录

一、主机与服务器的映射

1.修改本地 C:\Windows\System32\drivers\etc\hosts文件

在下面添加一条“ 阿里云的外网ip 主机名 ” 字段


2.修改阿里云服务器上的 /etc/hosts文件的外网IP地址修改为内网IP地址

3.重启zookeeper,再尝试连接

二、阿里云服务器端口未开放

1.进入阿里云ECS实例控制台

2.选择更多-安全组配置

3.选择配置规则

4.选择添加安全组规则

5.添加安全组规则

可根据需要选择协议类型及设置对应端口范围,为了省事,我选择协议类型为全部。点击确定,安全组规则设置完成。

三、修改zookeeper配置参数

在每一个zookeeper节点下的zoo.cfg配置文件中加入参数quorumListenOnAllIPs=true
然后再重启zookeeper集群,就可以正常连接了

quorumListenOnAllIPs:默认为false,如果设为true,zk服务器会监听所有可达IP上的连接。
在本地虚拟机部署时,不需要设置就可以连接,但是在阿里云上部署就不行了。找了好久才发现这个原因。目前还不是太懂这个的原理,反正外网连接设置上就对了