首页 > 其他分享 >curator操做zookeeper案例

curator操做zookeeper案例

时间:2024-02-15 11:56:34浏览次数:23  
标签:String zookeeper curator System 案例 println import public out

Apache Curator客户端的使用

curator与客户端的异同

zk原生api的不足之处

watch注册一次后就会失效

不支持递归创建节点

会话连接、命名空间和节点创建,递归创建,递归删除

package com.imooc.curator;

import java.util.List;

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.RetryNTimes;

public class CuratorOperator {

	public CuratorFramework client = null;
	public static final String zkServerPath = "192.168.1.110:2181";

	/**
	 * 实例化zk客户端
	 */
	public CuratorOperator() {
		/**
		 * 同步创建zk示例,原生api是异步的
		 * 
		 * curator链接zookeeper的策略:ExponentialBackoffRetry
		 * baseSleepTimeMs:初始sleep的时间
		 * maxRetries:最大重试次数
		 * maxSleepMs:最大重试时间
		 */
//		RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 5);
		
		/**
		 * curator链接zookeeper的策略:RetryNTimes
		 * n:重试的次数
		 * sleepMsBetweenRetries:每次重试间隔的时间
		 */
		RetryPolicy retryPolicy = new RetryNTimes(3, 5000);
		
		/**
		 * curator链接zookeeper的策略:RetryOneTime
		 * sleepMsBetweenRetry:每次重试间隔的时间
		 */
//		RetryPolicy retryPolicy2 = new RetryOneTime(3000);
		
		/**
		 * 永远重试,不推荐使用
		 */
//		RetryPolicy retryPolicy3 = new RetryForever(retryIntervalMs)
		
		/**
		 * curator链接zookeeper的策略:RetryUntilElapsed
		 * maxElapsedTimeMs:最大重试时间
		 * sleepMsBetweenRetries:每次重试间隔
		 * 重试时间超过maxElapsedTimeMs后,就不再重试
		 */
//		RetryPolicy retryPolicy4 = new RetryUntilElapsed(2000, 3000);
		
		client = CuratorFrameworkFactory.builder()
				.connectString(zkServerPath)
				.sessionTimeoutMs(10000).retryPolicy(retryPolicy)
				.namespace("workspace").build();
		client.start();
	}
	
	/**
	 * 
	 * @Description: 关闭zk客户端连接
	 */
	public void closeZKClient() {
		if (client != null) {
			this.client.close();
		}
	}
	
	public static void main(String[] args) throws Exception {
		// 实例化
		CuratorOperator cto = new CuratorOperator();
		boolean isZkCuratorStarted = cto.client.isStarted();
		System.out.println("当前客户的状态:" + (isZkCuratorStarted ? "连接中" : "已关闭"));
		
		// 创建节点
		String nodePath = "/super/imooc";
//		byte[] data = "superme".getBytes();
//		cto.client.create().creatingParentsIfNeeded()
//			.withMode(CreateMode.PERSISTENT)
//			.withACL(Ids.OPEN_ACL_UNSAFE)
//			.forPath(nodePath, data);
		
		// 更新节点数据
//		byte[] newData = "batman".getBytes();
//		cto.client.setData().withVersion(0).forPath(nodePath, newData);
		
		// 删除节点
//		cto.client.delete()
//				  .guaranteed()					// 如果删除失败,那么在后端还是继续会删除,直到成功
//				  .deletingChildrenIfNeeded()	// 如果有子节点,就删除
//				  .withVersion(0)
//				  .forPath(nodePath);
		
		
		
		// 读取节点数据
//		Stat stat = new Stat();
//		byte[] data = cto.client.getData().storingStatIn(stat).forPath(nodePath);
//		System.out.println("节点" + nodePath + "的数据为: " + new String(data));
//		System.out.println("该节点的版本号为: " + stat.getVersion());
		
		
		// 查询子节点
//		List<String> childNodes = cto.client.getChildren()
//											.forPath(nodePath);
//		System.out.println("开始打印子节点:");
//		for (String s : childNodes) {
//			System.out.println(s);
//		}
		
				
		// 判断节点是否存在,如果不存在则为空
//		Stat statExist = cto.client.checkExists().forPath(nodePath + "/abc");
//		System.out.println(statExist);
		
		
		// watcher 事件  当使用usingWatcher的时候,监听只会触发一次,监听完毕后就销毁
//		cto.client.getData().usingWatcher(new MyCuratorWatcher()).forPath(nodePath);
//		cto.client.getData().usingWatcher(new MyWatcher()).forPath(nodePath);
		
		// 为节点添加watcher,监听n次
		// NodeCache: 监听数据节点的变更,会触发事件
//		final NodeCache nodeCache = new NodeCache(cto.client, nodePath);
//		// buildInitial : 初始化的时候获取node的值并且缓存
//		nodeCache.start(true);
//		if (nodeCache.getCurrentData() != null) {
//			System.out.println("节点初始化数据为:" + new String(nodeCache.getCurrentData().getData()));
//		} else {
//			System.out.println("节点初始化数据为空...");
//		}
//		nodeCache.getListenable().addListener(new NodeCacheListener() {
//			public void nodeChanged() throws Exception {
//				if (nodeCache.getCurrentData() == null) {
//					System.out.println("空");
//					return;
//				}
//				String data = new String(nodeCache.getCurrentData().getData());
//				System.out.println("节点路径:" + nodeCache.getCurrentData().getPath() + "数据:" + data);
//			}
//		});
		
		
		// 为子节点添加watcher
		// PathChildrenCache: 监听数据节点的增删改,会触发事件
		String childNodePathCache =  nodePath;
		// cacheData: 设置缓存节点的数据状态
		final PathChildrenCache childrenCache = new PathChildrenCache(cto.client, childNodePathCache, true);
		/**
		 * StartMode: 初始化方式
		 * POST_INITIALIZED_EVENT:异步初始化,初始化之后会触发事件
		 * NORMAL:异步初始化
		 * BUILD_INITIAL_CACHE:同步初始化
		 */
		childrenCache.start(StartMode.POST_INITIALIZED_EVENT);
		
		List<ChildData> childDataList = childrenCache.getCurrentData();
		System.out.println("当前数据节点的子节点数据列表:");
		for (ChildData cd : childDataList) {
			String childData = new String(cd.getData());
			System.out.println(childData);
		}
		
		childrenCache.getListenable().addListener(new PathChildrenCacheListener() {
			public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
				if(event.getType().equals(PathChildrenCacheEvent.Type.INITIALIZED)){
					System.out.println("子节点初始化ok...");
				}
				
				else if(event.getType().equals(PathChildrenCacheEvent.Type.CHILD_ADDED)){
					String path = event.getData().getPath();
					if (path.equals(ADD_PATH)) {
						System.out.println("添加子节点:" + event.getData().getPath());
						System.out.println("子节点数据:" + new String(event.getData().getData()));
					} else if (path.equals("/super/imooc/e")) {
						System.out.println("添加不正确...");
					}
					
				}else if(event.getType().equals(PathChildrenCacheEvent.Type.CHILD_REMOVED)){
					System.out.println("删除子节点:" + event.getData().getPath());
				}else if(event.getType().equals(PathChildrenCacheEvent.Type.CHILD_UPDATED)){
					System.out.println("修改子节点路径:" + event.getData().getPath());
					System.out.println("修改子节点数据:" + new String(event.getData().getData()));
				}
			}
		});
		
		Thread.sleep(100000);
		
		cto.closeZKClient();
		boolean isZkCuratorStarted2 = cto.client.isStarted();
		System.out.println("当前客户的状态:" + (isZkCuratorStarted2 ? "连接中" : "已关闭"));
	}
	
	public final static String ADD_PATH = "/super/imooc/d";
	
}

package com.imooc.curator;

import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.zookeeper.WatchedEvent;

public class MyCuratorWatcher implements CuratorWatcher {

	@Override
	public void process(WatchedEvent event) throws Exception {
		System.out.println("触发watcher,节点路径为:" + event.getPath());
	}

}

package com.imooc.curator;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;

public class MyWatcher implements Watcher {

	@Override
	public void process(WatchedEvent event) {
		System.out.println("触发watcher,节点路径为:" + event.getPath());
	}


}

watch统一更新n台节点

package com.imooc.curator.checkConfig;

import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.commons.lang3.StringUtils;
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.NodeCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.framework.recipes.cache.PathChildrenCache.StartMode;
import org.apache.curator.retry.RetryNTimes;

import com.imooc.utils.JsonUtils;
import com.imooc.utils.RedisConfig;

public class Client1 {

	public CuratorFramework client = null;
	public static final String zkServerPath = "192.168.1.110:2181";

	public Client1() {
		RetryPolicy retryPolicy = new RetryNTimes(3, 5000);
		client = CuratorFrameworkFactory.builder()
				.connectString(zkServerPath)
				.sessionTimeoutMs(10000).retryPolicy(retryPolicy)
				.namespace("workspace").build();
		client.start();
	}
	
	public void closeZKClient() {
		if (client != null) {
			this.client.close();
		}
	}
	
//	public final static String CONFIG_NODE = "/super/imooc/redis-config";
	public final static String CONFIG_NODE_PATH = "/super/imooc";
	public final static String SUB_PATH = "/redis-config";
	public static CountDownLatch countDown = new CountDownLatch(1);
	
	public static void main(String[] args) throws Exception {
		Client1 cto = new Client1();
		System.out.println("client1 启动成功...");
		
		final PathChildrenCache childrenCache = new PathChildrenCache(cto.client, CONFIG_NODE_PATH, true);
		childrenCache.start(StartMode.BUILD_INITIAL_CACHE);
		
		// 添加监听事件
		childrenCache.getListenable().addListener(new PathChildrenCacheListener() {
			public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
				// 监听节点变化
				if(event.getType().equals(PathChildrenCacheEvent.Type.CHILD_UPDATED)){
					String configNodePath = event.getData().getPath();
					if (configNodePath.equals(CONFIG_NODE_PATH + SUB_PATH)) {
						System.out.println("监听到配置发生变化,节点路径为:" + configNodePath);
						
						// 读取节点数据
						String jsonConfig = new String(event.getData().getData());
						System.out.println("节点" + CONFIG_NODE_PATH + "的数据为: " + jsonConfig);
						
						// 从json转换配置
						RedisConfig redisConfig = null;
						if (StringUtils.isNotBlank(jsonConfig)) {
							redisConfig = JsonUtils.jsonToPojo(jsonConfig, RedisConfig.class);
						}
						
						// 配置不为空则进行相应操作
						if (redisConfig != null) {
							String type = redisConfig.getType();
							String url = redisConfig.getUrl();
							String remark = redisConfig.getRemark();
							// 判断事件
							if (type.equals("add")) {
								System.out.println("监听到新增的配置,准备下载...");
								// ... 连接ftp服务器,根据url找到相应的配置
								Thread.sleep(500);
								System.out.println("开始下载新的配置文件,下载路径为<" + url + ">");
								// ... 下载配置到你指定的目录
								Thread.sleep(1000);
								System.out.println("下载成功,已经添加到项目中");
								// ... 拷贝文件到项目目录
							} else if (type.equals("update")) {
								System.out.println("监听到更新的配置,准备下载...");
								// ... 连接ftp服务器,根据url找到相应的配置
								Thread.sleep(500);
								System.out.println("开始下载配置文件,下载路径为<" + url + ">");
								// ... 下载配置到你指定的目录
								Thread.sleep(1000);
								System.out.println("下载成功...");
								System.out.println("删除项目中原配置文件...");
								Thread.sleep(100);
								// ... 删除原文件
								System.out.println("拷贝配置文件到项目目录...");
								// ... 拷贝文件到项目目录
							} else if (type.equals("delete")) {
								System.out.println("监听到需要删除配置");
								System.out.println("删除项目中原配置文件...");
							}
							
							// TODO 视情况统一重启服务
						}
					}
				}
			}
		});
		
		countDown.await();
		
		cto.closeZKClient();
	}
	
}


package com.imooc.curator.checkConfig;

import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.commons.lang3.StringUtils;
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.NodeCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.framework.recipes.cache.PathChildrenCache.StartMode;
import org.apache.curator.retry.RetryNTimes;

import com.imooc.utils.JsonUtils;
import com.imooc.utils.RedisConfig;

public class Client2 {

	public CuratorFramework client = null;
	public static final String zkServerPath = "192.168.1.110:2181";

	public Client2() {
		RetryPolicy retryPolicy = new RetryNTimes(3, 5000);
		client = CuratorFrameworkFactory.builder()
				.connectString(zkServerPath)
				.sessionTimeoutMs(10000).retryPolicy(retryPolicy)
				.namespace("workspace").build();
		client.start();
	}
	
	public void closeZKClient() {
		if (client != null) {
			this.client.close();
		}
	}
	
//	public final static String CONFIG_NODE = "/super/imooc/redis-config";
	public final static String CONFIG_NODE_PATH = "/super/imooc";
	public final static String SUB_PATH = "/redis-config";
	public static CountDownLatch countDown = new CountDownLatch(1);
	
	public static void main(String[] args) throws Exception {
		Client2 cto = new Client2();
		System.out.println("client2 启动成功...");
		
		final PathChildrenCache childrenCache = new PathChildrenCache(cto.client, CONFIG_NODE_PATH, true);
		childrenCache.start(StartMode.BUILD_INITIAL_CACHE);
		
		// 添加监听事件
		childrenCache.getListenable().addListener(new PathChildrenCacheListener() {
			public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
				// 监听节点变化
				if(event.getType().equals(PathChildrenCacheEvent.Type.CHILD_UPDATED)){
					String configNodePath = event.getData().getPath();
					if (configNodePath.equals(CONFIG_NODE_PATH + SUB_PATH)) {
						System.out.println("监听到配置发生变化,节点路径为:" + configNodePath);
						
						// 读取节点数据
						String jsonConfig = new String(event.getData().getData());
						System.out.println("节点" + CONFIG_NODE_PATH + "的数据为: " + jsonConfig);
						
						// 从json转换配置
						RedisConfig redisConfig = null;
						if (StringUtils.isNotBlank(jsonConfig)) {
							redisConfig = JsonUtils.jsonToPojo(jsonConfig, RedisConfig.class);
						}
						
						// 配置不为空则进行相应操作
						if (redisConfig != null) {
							String type = redisConfig.getType();
							String url = redisConfig.getUrl();
							String remark = redisConfig.getRemark();
							// 判断事件
							if (type.equals("add")) {
								System.out.println("监听到新增的配置,准备下载...");
								// ... 连接ftp服务器,根据url找到相应的配置
								Thread.sleep(500);
								System.out.println("开始下载新的配置文件,下载路径为<" + url + ">");
								// ... 下载配置到你指定的目录
								Thread.sleep(1000);
								System.out.println("下载成功,已经添加到项目中");
								// ... 拷贝文件到项目目录
							} else if (type.equals("update")) {
								System.out.println("监听到更新的配置,准备下载...");
								// ... 连接ftp服务器,根据url找到相应的配置
								Thread.sleep(500);
								System.out.println("开始下载配置文件,下载路径为<" + url + ">");
								// ... 下载配置到你指定的目录
								Thread.sleep(1000);
								System.out.println("下载成功...");
								System.out.println("删除项目中原配置文件...");
								Thread.sleep(100);
								// ... 删除原文件
								System.out.println("拷贝配置文件到项目目录...");
								// ... 拷贝文件到项目目录
							} else if (type.equals("delete")) {
								System.out.println("监听到需要删除配置");
								System.out.println("删除项目中原配置文件...");
							}
							
							// TODO 视情况统一重启服务
						}
					}
				}
			}
		});
		
		countDown.await();
		
		cto.closeZKClient();
	}
	
}


package com.imooc.curator.checkConfig;

import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.commons.lang3.StringUtils;
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.NodeCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.framework.recipes.cache.PathChildrenCache.StartMode;
import org.apache.curator.retry.RetryNTimes;

import com.imooc.utils.JsonUtils;
import com.imooc.utils.RedisConfig;

public class Client3 {

	public CuratorFramework client = null;
	public static final String zkServerPath = "192.168.1.110:2181";

	public Client3() {
		RetryPolicy retryPolicy = new RetryNTimes(3, 5000);
		client = CuratorFrameworkFactory.builder()
				.connectString(zkServerPath)
				.sessionTimeoutMs(10000).retryPolicy(retryPolicy)
				.namespace("workspace").build();
		client.start();
	}
	
	public void closeZKClient() {
		if (client != null) {
			this.client.close();
		}
	}
	
//	public final static String CONFIG_NODE = "/super/imooc/redis-config";
	public final static String CONFIG_NODE_PATH = "/super/imooc";
	public final static String SUB_PATH = "/redis-config";
	public static CountDownLatch countDown = new CountDownLatch(1);
	
	public static void main(String[] args) throws Exception {
		Client3 cto = new Client3();
		System.out.println("client3 启动成功...");
		
		final PathChildrenCache childrenCache = new PathChildrenCache(cto.client, CONFIG_NODE_PATH, true);
		childrenCache.start(StartMode.BUILD_INITIAL_CACHE);
		
		// 添加监听事件
		childrenCache.getListenable().addListener(new PathChildrenCacheListener() {
			public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
				// 监听节点变化
				if(event.getType().equals(PathChildrenCacheEvent.Type.CHILD_UPDATED)){
					String configNodePath = event.getData().getPath();
					if (configNodePath.equals(CONFIG_NODE_PATH + SUB_PATH)) {
						System.out.println("监听到配置发生变化,节点路径为:" + configNodePath);
						
						// 读取节点数据
						String jsonConfig = new String(event.getData().getData());
						System.out.println("节点" + CONFIG_NODE_PATH + "的数据为: " + jsonConfig);
						
						// 从json转换配置
						RedisConfig redisConfig = null;
						if (StringUtils.isNotBlank(jsonConfig)) {
							redisConfig = JsonUtils.jsonToPojo(jsonConfig, RedisConfig.class);
						}
						
						// 配置不为空则进行相应操作
						if (redisConfig != null) {
							String type = redisConfig.getType();
							String url = redisConfig.getUrl();
							String remark = redisConfig.getRemark();
							// 判断事件
							if (type.equals("add")) {
								System.out.println("监听到新增的配置,准备下载...");
								// ... 连接ftp服务器,根据url找到相应的配置
								Thread.sleep(500);
								System.out.println("开始下载新的配置文件,下载路径为<" + url + ">");
								// ... 下载配置到你指定的目录
								Thread.sleep(1000);
								System.out.println("下载成功,已经添加到项目中");
								// ... 拷贝文件到项目目录
							} else if (type.equals("update")) {
								System.out.println("监听到更新的配置,准备下载...");
								// ... 连接ftp服务器,根据url找到相应的配置
								Thread.sleep(500);
								System.out.println("开始下载配置文件,下载路径为<" + url + ">");
								// ... 下载配置到你指定的目录
								Thread.sleep(1000);
								System.out.println("下载成功...");
								System.out.println("删除项目中原配置文件...");
								Thread.sleep(100);
								// ... 删除原文件
								System.out.println("拷贝配置文件到项目目录...");
								// ... 拷贝文件到项目目录
							} else if (type.equals("delete")) {
								System.out.println("监听到需要删除配置");
								System.out.println("删除项目中原配置文件...");
							}
							
							// TODO 视情况统一重启服务
						}
					}
				}
			}
		});
		
		countDown.await();
		
		cto.closeZKClient();
	}
	
}


package com.imooc.utils;

public class RedisConfig {

	private String type;	// add 新增配置	update 更新配置	delete 删除配置
	private String url;		// 如果是add或update,则提供下载地址
	private String remark;	// 备注
	
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public String getRemark() {
		return remark;
	}
	public void setRemark(String remark) {
		this.remark = remark;
	}
}

package com.imooc.utils;

import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 
 * @Title: JsonUtils.java
 * @Package com.lee.utils
 * @Description: JSON/对象转换类
 * Copyright: Copyright (c) 2016
 * Company:Nathan.Lee.Salvatore
 * 
 * @author leechenxiang
 * @date 2016年4月29日 下午11:05:03
 * @version V1.0
 */
public class JsonUtils {

    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 将对象转换成json字符串。
     * <p>Title: pojoToJson</p>
     * <p>Description: </p>
     * @param data
     * @return
     */
    public static String objectToJson(Object data) {
    	try {
			String string = MAPPER.writeValueAsString(data);
			return string;
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
    	return null;
    }
    
    /**
     * 将json结果集转化为对象
     * 
     * @param jsonData json数据
     * @param clazz 对象中的object类型
     * @return
     */
    public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
        try {
            T t = MAPPER.readValue(jsonData, beanType);
            return t;
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 将json数据转换成pojo对象list
     * <p>Title: jsonToList</p>
     * <p>Description: </p>
     * @param jsonData
     * @param beanType
     * @return
     */
    public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
    	JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
    	try {
    		List<T> list = MAPPER.readValue(jsonData, javaType);
    		return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    	return null;
    }
    
}

curator的acl权限与认证授权

递归创建acl

package com.imooc.curator;

import java.util.ArrayList;
import java.util.List;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooDefs.Perms;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;

import com.imooc.utils.AclUtils;

public class CuratorAcl {

	public CuratorFramework client = null;
	public static final String zkServerPath = "192.168.1.110:2181";

	public CuratorAcl() {
		RetryPolicy retryPolicy = new RetryNTimes(3, 5000);
		client = CuratorFrameworkFactory.builder().authorization("digest", "imooc1:123456".getBytes())
				.connectString(zkServerPath)
				.sessionTimeoutMs(10000).retryPolicy(retryPolicy)
				.namespace("workspace").build();
		client.start();
	}
	
	public void closeZKClient() {
		if (client != null) {
			this.client.close();
		}
	}
	
	public static void main(String[] args) throws Exception {
		// 实例化
		CuratorAcl cto = new CuratorAcl();
		boolean isZkCuratorStarted = cto.client.isStarted();
		System.out.println("当前客户的状态:" + (isZkCuratorStarted ? "连接中" : "已关闭"));
		
		String nodePath = "/acl/father/child/sub";
		
		List<ACL> acls = new ArrayList<ACL>();
		Id imooc1 = new Id("digest", AclUtils.getDigestUserPwd("imooc1:123456"));
		Id imooc2 = new Id("digest", AclUtils.getDigestUserPwd("imooc2:123456"));
		acls.add(new ACL(Perms.ALL, imooc1));
		acls.add(new ACL(Perms.READ, imooc2));
		acls.add(new ACL(Perms.DELETE | Perms.CREATE, imooc2));
		
		// 创建节点
//		byte[] data = "spiderman".getBytes();
//		cto.client.create().creatingParentsIfNeeded()
//				.withMode(CreateMode.PERSISTENT)
//				.withACL(acls, true)
//				.forPath(nodePath, data);
		

		cto.client.setACL().withACL(acls).forPath("/curatorNode");
		
		// 更新节点数据
//		byte[] newData = "batman".getBytes();
//		cto.client.setData().withVersion(0).forPath(nodePath, newData);
		
		// 删除节点
//		cto.client.delete().guaranteed().deletingChildrenIfNeeded().withVersion(0).forPath(nodePath);
		
		// 读取节点数据
//		Stat stat = new Stat();
//		byte[] data = cto.client.getData().storingStatIn(stat).forPath(nodePath);
//		System.out.println("节点" + nodePath + "的数据为: " + new String(data));
//		System.out.println("该节点的版本号为: " + stat.getVersion());
		
		
		cto.closeZKClient();
		boolean isZkCuratorStarted2 = cto.client.isStarted();
		System.out.println("当前客户的状态:" + (isZkCuratorStarted2 ? "连接中" : "已关闭"));
	}
	
}

package com.imooc.utils;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.server.auth.DigestAuthenticationProvider;

public class AclUtils {
	
	public static String getDigestUserPwd(String id) {
		String digest = "";
		try {
			digest = DigestAuthenticationProvider.generateDigest(id);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return digest;
	}
	
	public static void main(String[] args) throws IOException, InterruptedException, KeeperException, Exception {
		String id = "imooc:imooc";
		String idDigested = getDigestUserPwd(id);
		System.out.println(idDigested);
	}
}

标签:String,zookeeper,curator,System,案例,println,import,public,out
From: https://www.cnblogs.com/15078480385zyc/p/18016107

相关文章

  • 爬虫案例
    多进程和多线程爬虫案例importos.pathimporttimefrommultiprocessingimportProcessfromthreadingimportThreadimportrequestsfromlxmlimportetreefromfake_useragentimportUserAgentclassBaseSpider(object):def__init__(self):self.url......
  • zookeeper虚拟机使用和java api使用zookeeper案例
    zookeeper动物园管理员中间件,提供协调服务作用于分布式系统,发挥其优势,可以为大数据服务支持java,提供java和c语言的客户端api什么是分布式系统?很多台计算机组成一个整体,一个整体一致对外并且处理同一请求内部的每台计算机都可以相互通信(rest/rpc)客户端到服务端的一次请求到......
  • 非对称加密的经典案例-ssh密码登录/免密登录
    我在给云服务器配置本地电脑免密登录的过程中,学习了一下SSH免密登录的实现原理。对SSH中输入密码登录和免密登录的原理根据自己的理解做了如下笔记,分享给大家希望能有所帮助。1.对称加密对称加密是加密过程中只有一个密钥,加密解密都只用这个密钥。加密通讯至少要有一对通讯对......
  • Java后端项目实现无限级树 - 案例:部门树 - Department实体类
    privateList<Department>getDeptTree(){   //1.一次性查询出所有数据,放到内存中,可以使用map - 做缓存用   //2.从所有数据中找出第一层级/顶级部门:这就是我们需要返回的数据   //3.遍历所有部门只要不是第一层级的,找自己的上级,并将自己放入上级的childre......
  • JS使用EditableProTable案例
    EditableProTable是AntDesignPro中的一个可编辑表格组件,可以方便地实现表格数据的编辑和更新。下面是一个简单的示例,演示如何在React中使用EditableProTable组件:首先,确保你已经安装了AntDesignPro相关的依赖包。然后,可以按照以下步骤创建一个简单的可编辑表格:1、创......
  • 使用JS来开发ProComponents的ProTable案例
    ProComponents的ProTable组件是基于React和TypeScript开发的,但也可以在JavaScript项目中使用。以下是一个使用JavaScript的ProTable示例:import{useState,useRef}from'react';import{Button}from'antd';importProTablefrom'@ant-design/pro-table&#......
  • Profinet转CANopen主站网关与堡盟编码器通讯案例
    Profinet转CANopen主站网关与堡盟编码器通讯案例Profinet转CANopen主站网关(XD-COPNm20)为CPU与堡盟编码器的通讯提供了CANopen协议向Profinet协议转换互通的桥梁。CANopen是一种基于CAN总线的通讯协议,它被广泛应用于工业自动化领域,而Profinet是一种以太网协议,其优点是高速传输和......
  • 客户案例分享——大型装备制造企业的CRM应用
    本期,小Z为大家带来的CRM管理系统客户案例是某大型装备制造企业运用ZohoCRM管理全球业务的过程分享。该企业是创业板上市公司,业务遍及100多个国家和地区,合作伙伴超百位,拥有覆盖全球的销售和服务网络。截止目前,相继获得国家知识产权优势企业、国家级专精特新“小巨人”企业等多项......
  • 用户登录案例和form-serialize
    目录用户登录案例主要功能一基于axios提交用户名和密码并判断登录结果案例-用户登录提示框的样式form-serialize使用用户登录案例需求:1.点击登录时,判断用户名和密码的长度用户名要求:最少8位,中英文和数字组成密码:最少6位2.提交数据和服务器通信3.提示登录情况主要功能一判......
  • Zookeeper快速了解
    初识ZookeeperZookeeper是ApacheHadoop项目下的一个子项目,是一个树形目录服务。Zookeeper翻译过来就是动物园管理员,他是用来管Hadoop(大象)、Hive(蜜蜂)、Pig(小猪)的管理员。简称zkZookeeper是一个分布式的、开源的分布式应用程序的协调服务。Zookeeper提供的......