基于zkdash下Zookeeper完成CRUD及监听

      本文主要介绍在zkdash下实现zookeeper的CRUD及监听。


一、环境准备

(1)完全分布式环境,搭建过程可以参考我的另外一篇博客

《Hadoop完全分布式的搭建》

(2)安装Zookeeper,安装过程可以参考我的另外一篇博客

《完全分布式下安装Zookeeper》

(3)安装MySQL,安装过程可以参考我的另外一篇博客

《Linux下安装MySQL》

(4)安装zkdash,安装过程可以参考我的另外一篇博客

《Hadoop环境下安装zkdash》


二、启动Zookeeper,查看各个节点的状态





三、编写代码实现CRUD及监听

pom.xml文件:

<!-- https://mvnrepository.com/artifact/org.apache.curator/curator-recipes -->
	<dependency>
      <groupId>org.apache.curator</groupId>
      <artifactId>curator-recipes</artifactId>
      <version>2.12.0</version>
	</dependency>
	
	  <!-- https://mvnrepository.com/artifact/org.apache.curator/curator-framework -->
	<dependency>
      <groupId>org.apache.curator</groupId>
      <artifactId>curator-framework</artifactId>
      <version>2.12.0</version>
	</dependency>

测试代码:

package com.xzw.zookeeper;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCache.StartMode;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
/**
 * 
 * @author xzw
 *
 */
public class ZooCurator {
	private static String connectString = "192.168.100.68:2181,192.168.100.78:2181,192.168.100.88:2181/testZk";
	private static CuratorFramework client;
	private static String rootPath = "/";
	private static String tmpPath = "/zkTmpAdd";
	private static String ghPath = "zkAddByCurator";
	
	/**
	 * 创建一个Zookeeper连接
	 * @return
	 */
	private static CuratorFramework clientStart(){
		//连接时间和重试次数
		RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
		client = CuratorFrameworkFactory.newClient(connectString, retryPolicy);
		client.start();
		return client;
	}
	
	/**
	 * 添加一个节点
	 */
	public static void testAdd(){
		String addPath = "/zkAddByCurator";
		try {
			Stat checkStat = client.checkExists().forPath(addPath);
			if (checkStat == null) {
				client.create().forPath(addPath);
				client.setData().forPath(addPath,"通过Curator自动添加".getBytes("UTF-8"));
			}else {
				System.out.println(addPath + "路径已经存在");
			}
			addPath = "/zkTmpAdd";
			checkStat = client.checkExists().forPath(addPath);
			if (checkStat == null) {
				System.out.println(addPath + "路径尚不存在");
				client.create().withMode(CreateMode.EPHEMERAL).forPath(addPath,"temp add then delete it by zk".getBytes());
			}else {
				System.out.println(addPath + "路径已经存在");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 显示当前节点和子节点
	 */
	public static void testListSub(){
		try {
			List<String> subNodes = client.getChildren().forPath("/");
			System.out.println("当前节点和子节点:" + subNodes);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 实现CRUD及监听
	 * @param client
	 * @throws Exception
	 */
	public static void setListenterForCluster(CuratorFramework client) throws Exception{
		ExecutorService pool = Executors.newCachedThreadPool();
		PathChildrenCache childrenCache = new PathChildrenCache(client, rootPath, true);
		PathChildrenCacheListener childrenCacheListener = new PathChildrenCacheListener() {
			
			@Override
			public void childEvent(CuratorFramework client, PathChildrenCacheEvent event)
					throws Exception {
				ChildData data = event.getData();
				switch (event.getType()) {
					case CHILD_UPDATED:{
						System.out.println("CHILD_UPDATED:" + data.getPath() + ",数据:" + new String(data.getData()));
						break;
					}
					case CHILD_ADDED:{
						String realPath = data.getPath().substring(rootPath.length());
						if (realPath.equals(ghPath)) {
							System.out.println(ghPath + "新节点添加");
						}else if (realPath.equals(tmpPath)) {
							System.out.println(tmpPath + "新节点添加");
						}
						System.out.println("CHILD_ADDED:" + data.getPath() + ",数据:" + new String(data.getData()));
						break;
					}
					case CHILD_REMOVED:{
						String realPath = data.getPath().substring(rootPath.length());
						if (realPath.equals(ghPath)) {
							System.out.println(ghPath + "新节点删除");
						}else if (realPath.equals(tmpPath)) {
							System.out.println(tmpPath + "新节点删除");
						}
						System.out.println("CHILD_REMOVED:" + data.getPath() + ",数据:" + new String(data.getData()));
						break;
					}
					default:
						break;
				}
				
			}
		};
		childrenCache.getListenable().addListener(childrenCacheListener);
		System.out.println("Register zk watcher successfully!!!");
		childrenCache.start(StartMode.POST_INITIALIZED_EVENT);
	}
	
	public static void main(String[] args) throws Exception {
		CuratorFramework client = clientStart();
		testAdd();
		testListSub();
		setListenterForCluster(client);
		Thread.sleep(Long.MAX_VALUE);
	}

}


四、测试结果

(1)



(2)




      至此,基于zkdash下Zookeeper完成CRUD及监听就讲解完了,是不是感觉也没有那么难,快点动手试一下吧。


你们在此过程中还遇到了什么问题,欢迎留言,让我看看你们都遇到了哪些问题。

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

象在舞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值