①. zk是由java编写的需要java运行环境,所以大家首先要安装JDK
具体安装步骤,不再赘述
②. 首先进入zk的conf目录,将zoo_sample.cfg文件改名为zoo.cfg,并修改内容
tickTime=2000 #ZK中的一个时间单元。ZK中所有时间都是以这个时间单元为基础,进行整数倍配置的。例如,session的最小超时时间是2*tickTime。 initLimit=5 #Leader允许Follower在 initLimit 时间内完成这个工作 syncLimit=2 #心跳检测,Leader发出心跳包在syncLimit之后,还没有从F那里收到响应,那么就认为这个F已经不在线了 dataDir=/usr/local/zookeeper/data #我们需要在此目录下创建myid用于标识zk节点,对应server.x,事务日志也会存储在这里 dataLogDir=/usr/local/zookeeper/logs #事务日志输出目录 clientPort=2181 #对外提供的端口号,默认2181 server.1=zk1:2888:3888 #server.x跟myid对应,两个通信端口第一个端口用于F和L之间的数据同步和其它通信,第二个端口用于Leader选举过程中投票通信。 server.2=zk2:2888:3888 server.3=zk3:2888:3888
③. 设置myid, 在zk根目录创建前面zoo.cfg中配置的dataDir指定的文件夹,创建myid,myid中的值需与server.x保持一致
④. 都设置完之后,记得检查一下各节点端口是否打通,并且关闭防火墙
⑤. 进入bin目录,执行 sh zkServer.sh start & 命令,通过JPS检查是否启动,并且查看日志:
tail -fn 100 zookeeper.out,第一个节点启动,会报如下异常:
此时不做理会,当所有节点启动完成之后即恢复正常
2017-09-14 14:50:24,993 [myid:2] - INFO [QuorumPeer[myid=2]/0:0:0:0:0:0:0:0:2181:QuorumPeer$QuorumServer@149] - Resolved hostname: 192.168.116.127 to address: /zk2 2017-09-14 14:50:24,995 [myid:2] - WARN [QuorumPeer[myid=2]/0:0:0:0:0:0:0:0:2181:QuorumCnxManager@400] - Cannot open channel to 3 at election address /zk2:3888 java.net.ConnectException: 拒绝连接 at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:579) at org.apache.zookeeper.server.quorum.QuorumCnxManager.connectOne(QuorumCnxManager.java:381) at org.apache.zookeeper.server.quorum.QuorumCnxManager.connectAll(QuorumCnxManager.java:426) at org.apache.zookeeper.server.quorum.FastLeaderElection.lookForLeader(FastLeaderElection.java:843) at org.apache.zookeeper.server.quorum.QuorumPeer.run(QuorumPeer.java:822)
,使用 sh zkServer.sh status检查节点状态,一般myid大的为leader
客户端验证是否成功:
private final static String CONNECT_STRING = "zk1:2181,zk2:2181,zk3:2181"; private final static int SESSION_TIMEOUT = 2000; private ZooKeeper zk = null; @Before public void init() throws Exception { zk = new ZooKeeper(CONNECT_STRING, SESSION_TIMEOUT, new ZKWatcher()); } @Test public void create() throws Exception { String cResponse = zk.create("/app-01", "hello this is app-01 node".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); Thread.sleep(1000); System.out.println("--->create:" + cResponse); } @Test public void get() throws Exception { System.out.println(zk.getChildren("/", new ZKWatcher())); } @Test public void set() throws Exception { System.out.println(zk.setData("/app-01", "this is app-01 node.update count 4".getBytes(), -1)); } @Test public void getData() throws Exception { System.out.println(new String(zk.getData("/app-01/hello", new ZKWatcher(), null))); // Thread.sleep(Long.MAX_VALUE); }
或使用工具:ZooInspector连接,检查使用情况以及服务端状态