CuratorFramework client = CuratorFrameworkFactory.builder().namespace("MyApp") ... build(); … client.create().forPath("/test", data); // node was actually written to: "/MyApp/test"
//创建client CuratorFramework client = CuratorFrameworkFactory.newClient(ZK_SERVER, new ExponentialBackoffRetry(1000, 3)); client.start(); //节点创建 if (client.checkExists().forPath("/curator") == null) client.create().withMode(CreateMode.PERSISTENT).forPath("/curator"); //获取子节点 System.out.println(client.getChildren().forPath("/curator")); //设置并获取数据 client.setData().forPath("/curator", "zero".getBytes()); System.out.println(client.getData().forPath("/curator")); //删除节点 client.delete().forPath("/curator"); PathChildrenCache watcher = new PathChildrenCache(client, "/curator", true); watcher.getListenable().addListener(new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { ChildData data = event.getData(); if (data == null) { System.out.println("No data in event[" + event + "]"); } else { System.out.println("Receive event: " + "type=[" + event.getType() + "]" + ", path=[" + data.getPath() + "]" + ", data=[" + new String(data.getData()) + "]" + ", stat=[" + data.getStat() + "]"); } } }); watcher.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE); System.out.println("Register zk watcher successfully!");
队列(Queue)
分布式队列:采用持久顺序zk node来实现FIFO队列, 如果有多个消费者, 可以使用LeaderSelector来保证队列的消费者顺序。public class CuratorDistrLockTest { /** Zookeeper info */ private static final String ZK_ADDRESS = "192.168.1.100:2181"; private static final String ZK_LOCK_PATH = "/zktest"; public static void main(String[] args) throws InterruptedException { // 1.Connect to zk CuratorFramework client = CuratorFrameworkFactory.newClient( ZK_ADDRESS, new RetryNTimes(10, 5000) ); client.start(); System.out.println("zk client start successfully!"); Thread t1 = new Thread(() -> { doWithLock(client); }, "t1"); Thread t2 = new Thread(() -> { doWithLock(client); }, "t2"); t1.start(); t2.start(); } private static void doWithLock(CuratorFramework client) { InterProcessMutex lock = new InterProcessMutex(client, ZK_LOCK_PATH); try { if (lock.acquire(10 * 1000, TimeUnit.SECONDS)) { System.out.println(Thread.currentThread().getName() + " hold lock"); Thread.sleep(5000L); System.out.println(Thread.currentThread().getName() + " release lock"); } } catch (Exception e) { e.printStackTrace(); } finally { try { lock.release(); } catch (Exception e) { e.printStackTrace(); } } } }Leader选举
public static void LeaderSelectorTest() throws Exception { RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); final CuratorFramework client = CuratorFrameworkFactory.builder() .connectString(host).sessionTimeoutMs(5000) .connectionTimeoutMs(10000).retryPolicy(retryPolicy) .namespace(namespace).build(); client.start(); final LeaderSelector leaderSelector = new LeaderSelector(client, "/leader", new LeaderSelectorListenerAdapter() { @Override public void takeLeadership(CuratorFramework client) throws Exception { System.out.println("I am leader, working..."); TimeUnit.SECONDS.sleep(3); System.out.println("I am leader, end."); } }); leaderSelector.autoRequeue(); leaderSelector.start(); TimeUnit.SECONDS.sleep(1000); } public static void leaderLatchTest() throws Exception { RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); CuratorFramework client = CuratorFrameworkFactory.builder() .connectString(host).sessionTimeoutMs(2000) .connectionTimeoutMs(10000).retryPolicy(retryPolicy) .namespace(namespace).build(); client.start(); System.out.println("I want to be leader."); // 选举Leader 启动 LeaderLatch latch = new LeaderLatch(client, "/leader"); latch.start(); latch.await(); System.out.println("I am leader"); TimeUnit.SECONDS.sleep(10); latch.close(); client.close(); }