Zookeeper服务器集群搭建
访问量:
获取zookeeper
从apache zookeeper官网上获取zookeeper
https://www.apache.org/dyn/closer.cgi/zookeeper/
zkServer.sh
配置集群
可以在本机上模拟集群搭建,不同server用不同port即可。可以在 /conf目录下创建三个cfg文件:zoo1.cfg, zoo2,cfg, zoo3.cfg, 分别赋予 不同的clientPort(如2181,2182,2183)和dataDir (“./data/zk1”, “./data/zk2”, “./data/zk3”),其他的配置保持一致,具体配置如下
# The number of milliseconds of each tick
tickTime=2000
# The number of ticks that the initial
# synchronization phase can take
initLimit=10
# The number of ticks that can pass between
# sending a request and getting an acknowledgement
syncLimit=5
# the directory where the snapshot is stored.
# do not use /tmp for storage, /tmp here is just
# example sakes.
dataDir=./data/zk1
# the port at which the clients will connect
clientPort=2181
# the first port is for quorum communication, the second port is for leader election
server.1=localhost:2881:3881
server.2=localhost:2882:3882
server.3=localhost:2883:3883
在dataDir指定的路径下创建myid文件
$ echo 1 > ./data/zk1/myid
$ echo 2 > ./data/zk2/myid
$ echo 3 > ./data/zk3/myid
启动zk集群
$ bin/zkServer.sh start conf/zoo1.cfg
$ bin/zkServer.sh start conf/zoo2.cfg
$ bin/zkServer.sh start conf/zoo3.cfg
zk server的log会记录到zookeeper.out。如果为了方便测试查看server log,可以采用下面命令启动server
$ bin/zkServer.sh start-foreground conf/zoo1.cfg
集群测试
可以用zk自带的zkCli.sh对搭建的集群进行一些测试,如创建一个/tmp节点,然后添加test子节点数据。首先需要用zkCli.sh 连接到server。
...] create /tmp ""
...] create /tmp/test "abc"
...] get /tmp
...] get /tmp/test
...] delete /tmp/test
...] delete /tmp
zkCli.sh
通过zkCli.sh连接zookeeper服务器的命令
$ bin/zkCli.sh -server 127.0.0.1:2181
这种方式存在的问题是一旦2181端口对应的server挂掉,client会一直尝试连接,并且失败。当2181端口对应的server重启后,client会报连接失败, session过期,connection会被close掉, 所以-server参数最好带上所有的server地址。
$ bin/zkCli.sh -server 127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183
当zookeeper集群有server有机器挂掉,存在下面几种情况
- 如果client连接到的server挂了
- 该server是leader,则zookeeper在原来两个follower中重新选举leader后,client会连接到某台server上
- 该server是follower, client会与另外两台server建立连接
- 如果不是client连接的那台server挂了
- 如果挂的server是leader,由于要重新选举,client的connection会被refused,client尝试reconnect,选举成功后,client会再连接上, 和之前是同一个session
- 如果挂的server不是leader,client的连接不受任何影响
- 如果挂的server数目超过了多数,client将无法连接到server