ZooKeeper学习笔记四 ZooKeeper基本使用

Windows单机版本安装

下载zookeeper windows3.3.6
把conf/zoo_sample.cfg改名为zoo.cfg

# 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.
dataDir=D:\\tools\\zookeeper-3.3.6
dataLogDir=D:\\tools\\zookeeper-3.3.6
# the port at which the clients will connect
clientPort=2181

1、tickTime:这个时间是作为Zookeeper 服务器之间或客户端与服务器之间维持心跳的时间间隔,也就是每个 tickTime 时间就会发送一个心跳。

2、dataDir:顾名思义就是Zookeeper 保存数据的目录,默认情况下,Zookeeper 将写数据的日志文件也保存在这个目录里。

3、dataLogDir:顾名思义就是Zookeeper 保存日志文件的目录

4、clientPort:这个端口就是客户端连接Zookeeper 服务器的端口,Zookeeper 会监听这个端口,接受客户端的访问请求。

启动
进入到bin目录,并且启动zkServer.cmd

启动jps命令,会看到一个QuorumPeerMain进程 :
ZooKeeper学习笔记四 ZooKeeper基本使用_第1张图片

CentOS7 服务端安装

mkdir -p /usr/local/services/zookeeper
cd /usr/local/services/zookeeper
wget https://mirrors.tuna.tsinghua.edu.cn/apache/zookeeper/zookeeper-3.4.12/zookeeper-3.4.12.tar.gz
tar -zxvf zookeeper-3.4.9.tar.gz
cd zookeeper-3.4.9/conf/
cp zoo_sample.cfg zoo.cfg
vim zoo.cfg

修改:

# 数据文件夹
dataDir=/usr/local/services/zookeeper/zookeeper-3.4.12/data
 
# 日志文件夹
dataLogDir=/usr/local/services/zookeeper/zookeeper-3.4.12/logs

保存并退出。

cd ../bin/
vim /etc/profile

增加:


 
export ZOOKEEPER_HOME=/usr/local/services/zookeeper/zookeeper-3.4.12/
export PATH=$ZOOKEEPER_HOME/bin:$PATH
export PATH


保存并退出。

source /etc/profile
zkServer.sh start

命令:

# 查询状态
zkServer.sh status
# 关闭zookeeper
zkServer.sh stop
# 重启
zkServer.sh restart

设置自动启动

在/etc/rc.local文件中追加:

# java_home
#export JAVA_HOME=/usr/java/jdk1.8.0_66
# zookeeper
/usr/local/services/zookeeper/zookeeper-3.4.12/bin/zkServer.sh start

测试客户端

连接

zkCli -server 127.0.0.1:2181

创建节点

create [-s] [-e] path data acl

-s 或 -e分别指定节点特性,顺序或临时节点。默认情况下,创建的是持久节点。
acl是进行权限控制的。

create /zk-book 123    #创建/zk-book节点,内容是123

读取结点

ls /zk-book
ls /

读取内容

get path [watch]

更新结点
set path data [version]

删除

delete path [version]

注意 , 无法删除一个有子节点的节点。

Java客户端API使用

文档:http://zookeeper.apache.org/doc/r3.4.6/api/index.html

连接、查询

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;

public class ZooKeeper_Constructor_Usage_Simple {

	public static void main(String[] args) throws IOException {
		String hostPort = "localhost:2181";
	    String zpath = "/";
	    List  zooChildren = new ArrayList();
	    ZooKeeper zk = new ZooKeeper(hostPort, 2000, null);
	    if (zk != null) {
	      try {
	        zooChildren = zk.getChildren(zpath, false);
	        System.out.println("Znodes of '/': ");
	        for (String child: zooChildren) {
	          //print the children
	          System.out.println(child);
	        }
	      } catch (KeeperException e) {
	        e.printStackTrace();
	      } catch (InterruptedException e) {
	        e.printStackTrace();
	      }
	    }

	}

}

输出:
这里写图片描述

ZooKeeper的构造函数最多有5个参数:

ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, long sessionId, byte[] sessionPasswd)

创建结点

String create(final String path,
              byte data[],
              List acl,
              CreateMode createMode)
void create(final String path,
              byte data[],
              List acl,
              CreateMode createMode,
              StringCallback cb,Object ctx)

这两个接口分别以同步和异步方式创建节点。

目前ZooKeeper的节点的内容只支持字节数组类型,使用者需要自己进行序列化和反序列化。

package zookeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

public class ZooKeeper_Create_API_Sync_Usage implements Watcher {

	private static CountDownLatch connectedSemaphore = new CountDownLatch(1);
	public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
		String hostPort = "localhost:2181";
	    ZooKeeper zookeeper = new ZooKeeper(hostPort,5000,new ZooKeeper_Create_API_Sync_Usage());
	    connectedSemaphore.await();
	    String path1 = zookeeper.create("/zk-test-ephemeral-","".getBytes(),
	    		Ids.OPEN_ACL_UNSAFE,
	    		CreateMode.EPHEMERAL);
	    System.out.println("Success create znode:"+path1);
	    String path2 = zookeeper.create("/zk-test-ephemeral-","".getBytes(),Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);
	    System.out.println("Success create znode:"+path2);

	}

	@Override
	public void process(WatchedEvent event) {
		if(KeeperState.SyncConnected == event.getState()){
			connectedSemaphore.countDown();
		}
		
	}

}

结果:

Success create znode:/zk-test-ephemeral-
Success create znode:/zk-test-ephemeral-0000000020

使用同步API更新节点数据内容

package zookeeper;

import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class SetData_API_Sync_Usage implements Watcher {
	private static CountDownLatch connectedSemaphore = new CountDownLatch(1);
	private static ZooKeeper zk;
	
	public static void main(String[] args) throws Exception{
		String path = "/zk-book";
		zk = new ZooKeeper("127.0.0.1:2181",5000, new SetData_API_Sync_Usage());
		connectedSemaphore.await();

		zk.create(path, "123".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
		zk.getData(path, true, null);
		
		Stat stat = zk.setData(path,"456".getBytes(),-1);
		System.out.println(stat.getCzxid()+","+stat.getMzxid()+","+stat.getVersion());
		Stat stat2 = zk.setData(path, "456".getBytes(), stat.getVersion());
		System.out.println(stat2.getCzxid()+","+stat2.getMzxid()+"," + stat2.getVersion());
		
		try{
			zk.setData(path, "456".getBytes(), stat.getVersion());
		}catch(KeeperException e){
			System.out.println("Error:"+e.code() + "," + e.getMessage());
		}
		
	}
	public void process(WatchedEvent event){
		if(KeeperState.SyncConnected == event.getState()){
			if(EventType.None == event.getType() && null == event.getPath()){
				connectedSemaphore.countDown();
			}
		}
	}
}

异步更新
使用:async接口。

检测节点是否存在

public Stat exists(final String path,Watcher watcher)
public Stat exists(String path,boolean watch)
public void exists(final String path,Watcher watcher,StatCallback cb,Object ctx)
public void exists(String path,boolean watch,StatCallback cb,Object ctx)

权限控制
ZooKeeper客户端提供了接口进行权限控制:

addAuthInfo(String scheme,byte[] auth)

你可能感兴趣的:(架构)