Curator是一个开源的zookeeper客户端,解决了很多zookeeper原生客户端非常底层的细节开发工作,如连接重试、反复注册watcher等。
public class CuratorOperator { // zookeeper地址 private static final String zkServers = "127.0.0.1:2181"; private static final String path = "/mynode"; public static void main(String[] args) throws Exception { //重试策略 RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); //RetryPolicy retryPolicy = new RetryNTimes(5, 500); //1.创建zk客户端 //第一种方式 //CuratorFramework client = CuratorFrameworkFactory.newClient(zkServerPath, retryPolicy); //第二种方式 CuratorFramework client = CuratorFrameworkFactory.builder().connectString(zkServers) .sessionTimeoutMs(5000)//会话超时 .connectionTimeoutMs(5000)//连接超时 .retryPolicy(retryPolicy)//重试策略 .build(); //启动zk客户端 client.start(); //2.创建节点 String data = "hello"; client.create() .creatingParentsIfNeeded()//若创建节点的父节点不存在则会先创建父节点再创建子节点 .withMode(CreateMode.EPHEMERAL)//节点类型 .forPath(path, data.getBytes()); //3.获取节点的所有子节点 System.out.println(client.getChildren().forPath("/")); //4.获取节点的数据 byte[] buf = client.getData().forPath(path); System.out.println(new String(buf)); //5.修改节点数据 String newData = "world"; client.setData().forPath(path, newData.getBytes()); buf = client.getData().forPath(path); System.out.println(new String(buf)); //6.删除节点 client.delete().forPath(path); System.out.println(client.getChildren().forPath("/")); //7.关闭zk客户端连接 if (client != null) { client.close(); } } }
原文:https://www.cnblogs.com/rouqinglangzi/p/11152598.html