Curator是Netflix公司开源的一套zookeeper客户端框架,解决了很多Zookeeper客户端非常底层的细节开发工作,里面提供了更多丰富的操作,例如session超时重连、主从选举、分布式计数器、分布式锁等等适用于各种复杂的zookeeper场景的API封装。
<dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-framework</artifactId> <version>2.11.0</version> </dependency> <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-recipes</artifactId> <version>2.11.0</version> </dependency>
public class CuratorClientUtils { private static String ZK_URL = "192.168.1.45:2181,192.168.1.46:2181,192.168.1.41:2181"; private static CuratorFramework curatorFramework = null; public static CuratorFramework getCuratorFramework(){ if (curatorFramework == null){ curatorFramework = CuratorFrameworkFactory.newClient(ZK_URL, 5000,5000, new ExponentialBackoffRetry(1000,5)); } curatorFramework.start(); return curatorFramework; } }
public class CuratorApiDemo { public static void main(String[] args) throws Exception { CuratorFramework curatorFramework = CuratorClientUtils.getCuratorFramework(); //fluent模式,优雅的模式 /** * 新增,递归创建,CreateMode.PERSISTENT 创建持久化节点(默认), */ String path = curatorFramework.create().creatingParentsIfNeeded() .withMode(CreateMode.PERSISTENT).forPath("/node/node1","123".getBytes()); System.out.println(path); byte[] nodeBytes = curatorFramework.getData().forPath("/node"); System.out.println("node的值:"+new String(nodeBytes)); /** * 修改,如果第二个参数不填 会被修改为本机IP */ curatorFramework.setData().forPath("/node/node1","node1".getBytes()); /** * 获取stat信息 */ Stat stat=new Stat(); byte[] bytes = curatorFramework.getData().storingStatIn(stat).forPath("/node/node1"); System.out.println("修改后的值:"+new String(bytes)+"-->"+stat); /** * 删除 */ Void aVoid = curatorFramework.delete().deletingChildrenIfNeeded().forPath("/node"); System.out.println(aVoid); /** * 事务操作(curator独有的), 不会创建成功! */ curatorFramework.inTransaction().create().withMode(CreateMode.PERSISTENT).forPath("/node","123".getBytes()) .and().setData().forPath("/curator","123".getBytes()); ExecutorService executorService = Executors.newFixedThreadPool(1); curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT) .inBackground(new BackgroundCallback() { public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception { System.out.println("接收到watcher回调"); System.out.println(Thread.currentThread().getName()+"->resultCode:"+curatorEvent.getResultCode()+"->" +curatorEvent.getType()); } },executorService).forPath("/node/node1"); System.in.read(); } }