javaAPI操作Zookeeper

一.JavaAPI操作zk## 标题

		步骤一:导入zk依赖
				<dependency>
				  <groupId>org.apache.zookeeper</groupId>
				  <artifactId>zookeeper</artifactId>
				  <version>3.4.6</version>
				</dependency>
		JavaAPI操作zk步骤:
			1.连接到zookeeper
					//zk连接地址  private static final String CONNECT_ADDR="192.168.7.66:2181,192.168.7.77:2181,192.168.7.88:2181";
					private static final String CONNECT_ADDR="127.0.0.1:2181";
					//zk连接超时时间,如果超过时间没有建立连接则不进行连接
					private static final Integer SESSION_TIME_OUT=2000;
					public static void main(String[] args) throws IOException, InterruptedException {
						/**
						 * 步骤一:连接到zookeeper
						 * 参数一:String path代表连接zk的地址
						 * 参数二:Integer SessionTimeOut 连接超时时间
						 * 参数三:Watcher 代表监听,可以监听连接,添加节点,修改节点等等操作
						 */
						ZooKeeper zooKeeper=new ZooKeeper(CONNECT_ADDR, SESSION_TIME_OUT, new Watcher() {
							//代表监听回调方法,如果不需要监听则方法内部可以没有任何实现代码
							//如果需要监听,则需要根据状态和类别进行监听
							//event代表操作事件
							@Override
							public void process(WatchedEvent event) {

							}
						});
						System.out.println("zk连接成功~");
						//关闭zk
						zooKeeper.close();
					}
			2.创建一个节点
/**
					 * 创建节点
					 * 参数一:节点路径地址
					 * 参数二:节点存放的值
					 * 参数三:权限
					 * 参数四:代表节点类型(持久/瞬时)
					 * 返回值:创建节点的实际路径
					 */
					String zNode = zooKeeper.create("/zNode", "zNodeValue".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
					System.out.println("创建节点返回值:"+zNode);
			3.修改节点
/**
				 * 修改节点
				 * 参数一:修改节点路径
				 * 参数二:修改节点的值
				 * 参数三:代表版本号
				 */
				Stat stat = zooKeeper.setData("/zNode", "zNodeNewValue".getBytes(), -1);
				System.out.println(stat.toString());
			4.删除节点
/**
				 * 删除节点
				 *      delete  需要一层一层删除
				 * 参数一:代表删除节点路径
				 * 参数二:代表版本,不知道为-1
				 */
				zooKeeper.delete("/zNode/zNodeChild",-1);
				System.out.println("删除成功~");
			5.获取节点
/**
					 * 获取子集节点
					 */
					List<String> children = zooKeeper.getChildren("/", false);
					for (String node:children) {
						System.out.println(node);
					}
					
					
					
					//获取节点值
					byte[] data = zooKeeper.getData("/zookeeper/quota", false, new Stat());
					System.out.println(new String(data));
				
			6.Watcher监听基础
public class ZookeeperDemo {
					//zk连接地址  private static final String CONNECT_ADDR="192.168.7.66:2181,192.168.7.77:2181,192.168.7.88:2181";
					private static final String CONNECT_ADDR="192.168.7.66:2181,192.168.7.77:2181,192.168.7.88:2181";
					//zk连接超时时间,如果超过时间没有建立连接则不进行连接
					private static final Integer SESSION_TIME_OUT=2000;
					//计数器,在JUC包下的  java.util.concurrent代表并发包,并发包中工具类可以控制并发线程访问以及资源
					//对一个线程进行监控,Watcher监听时会启动一个线程,当线程执行完毕后,将计数器-1
					private static CountDownLatch countDownLatch=new CountDownLatch(1);

					public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
						/**
						 * 步骤一:连接到zookeeper
						 * 参数一:String path代表连接zk的地址
						 * 参数二:Integer SessionTimeOut 连接超时时间
						 * 参数三:Watcher 代表监听,可以监听连接,添加节点,修改节点等等操作
						 */
						ZooKeeper zooKeeper=new ZooKeeper(CONNECT_ADDR, SESSION_TIME_OUT, new Watcher() {
							//代表监听回调方法,如果不需要监听则方法内部可以没有任何实现代码
							//如果需要监听,则需要根据状态和类别进行监听
							//event代表操作事件
							@Override
							public void process(WatchedEvent event) {
								//获取zk状态
								Event.KeeperState state = event.getState();
								//已经建立连接状态下
								if(state== Event.KeeperState.SyncConnected){
									//监听事件,监听连接还是增删改
									Event.EventType type = event.getType();
									if(type== Event.EventType.None){
										System.out.println("客户端与服务器建立了连接");
										//计数器-1,代表有一个线程执行结束
										countDownLatch.countDown();
									}
								}

							}
						});

						//线程等待,阻塞,等待计数器为0则放行
						countDownLatch.await();

						System.out.println("建立连接后,后续操作~");

						//关闭zk
						zooKeeper.close();
					}
				}
			7.事件监听
public class MyWatcher implements Watcher {
					//zk连接地址  private static final String CONNECT_ADDR="192.168.7.66:2181,192.168.7.77:2181,192.168.7.88:2181";
					private static final String CONNECT_ADDR="192.168.7.66:2181,192.168.7.77:2181,192.168.7.88:2181";
					//zk连接超时时间,如果超过时间没有建立连接则不进行连接
					private static final Integer SESSION_TIME_OUT=2000;
					private ZooKeeper zooKeeper = null;
					//对一个线程进行监控,Watcher监听时会启动一个线程,当线程执行完毕后,将计数器-1
					private static CountDownLatch countDownLatch=new CountDownLatch(1);

					//只要事件发生该表都会执行该回调方法
					@Override
					public void process(WatchedEvent event) {
						//获取事件类型和状态
						Event.EventType type = event.getType();
						Event.KeeperState state = event.getState();
						String path = event.getPath();
						System.out.println("zk状态:"+state+"\tzk类型:"+type+"\t操作地址:"+path);
						if(state == Event.KeeperState.SyncConnected){
							/**
							 * 监听连接状态
							 */
							if(type == Event.EventType.None){
								System.out.println("~~~~~~~~~~~~~~~~zk成功建立连接~~~~~~~~~~~~");
								countDownLatch.countDown();
							}else if(type == Event.EventType.NodeCreated){
								System.out.println("~~~~~~~~~~~~~~~~zk成功创建节点~~~~~~~~~~~~");
							}else if(type == Event.EventType.NodeDataChanged){
								System.out.println("~~~~~~~~~~~~~~~~zk成功修改节点数据~~~~~~~~~~~~");
							}else if(type == Event.EventType.NodeDeleted){
								System.out.println("~~~~~~~~~~~~~~~~zk成功删除节点数据~~~~~~~~~~~~");
							}else if(type == Event.EventType.NodeChildrenChanged){
								System.out.println("~~~~~~~~~~~~~~~~zk成功修改子节点数据~~~~~~~~~~~~");
							}
						}
					}
					/**
					 * 创建ZK连接方法
					 */
					public void createZkConnection(String connect_Addr,Integer session_Time_Out){
						try {
							zooKeeper = new ZooKeeper(connect_Addr, session_Time_Out, this);
						} catch (IOException e) {
							e.printStackTrace();
						}
					}

					/**
					 * 关闭zk连接
					 * @throws InterruptedException
					 */
					public void closeZkConnection(){
						if(zooKeeper!=null){
							try {
								zooKeeper.close();
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}

					public MyWatcher() {
						createZkConnection(CONNECT_ADDR,SESSION_TIME_OUT);
					}

					/**
					 * 创建节点
					 * @throws InterruptedException
					 */
					 public String createNode(String path,String value) throws KeeperException, InterruptedException {
						 //创建节点需要开启监听
						 zooKeeper.exists(path,true);
						 String node = zooKeeper.create(path, value.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
						 return node;
					 }

					/**
					 * 修改节点
					 * @param
					 * @throws InterruptedException
					 * @throws KeeperException
					 */
					public Stat setNodeData(String path,String value) throws KeeperException, InterruptedException {
						zooKeeper.exists(path,true);
						Stat stat = zooKeeper.setData(path, value.getBytes(), -1);
						return stat;
					}

					/**
					 * 删除节点
					 * @param path
					 * @throws KeeperException
					 * @throws InterruptedException
					 */
					public void deleteNode(String path) throws KeeperException, InterruptedException {
						zooKeeper.exists(path,true);
						zooKeeper.delete(path,-1);
					}


					public static void main(String[] args) throws InterruptedException, KeeperException {
						MyWatcher myWatcher=new MyWatcher();
						countDownLatch.await();
						myWatcher.createNode("/zNode/zNodeChild02", "zNodeValue");
						//System.out.println("创建节点返回结果:"+zNodeValue);
						//myWatcher.setNodeData("/zNode/zNodeChild","zValue");
						//myWatcher.deleteNode("/znode02");
						myWatcher.closeZkConnection();
					}
				}
			
好好学学天天向上
发布了5 篇原创文章 · 获赞 0 · 访问量 59
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 深蓝海洋 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览