zookeeper原生API及Curator的使用

原生API

节点特性

/**
 * zookeeper节点特性
 */
public class ZkDemo {
    public static void main(String[] args) {
        try {
            final CountDownLatch countDownLatch=new CountDownLatch(1);
            ZooKeeper zookeeper=new
                    ZooKeeper("192.168.3.140:2181,192.168.3.141:2181,192.168.3.142:2181", 4000, new Watcher() {
                public void process(WatchedEvent watchedEvent) {
                    if(Event.KeeperState.SyncConnected==watchedEvent.getState()){
                        countDownLatch.countDown();
                    }
                }
            });
            countDownLatch.await();
            System.out.println(zookeeper.getState());
                                //节点路径      值                 ACL(节点的操作权限)       节点的类型,持久化节点
            zookeeper.create("/zk-taofut","0".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            Thread.sleep(1000);
            Stat stat=new Stat();

            //得到当前节点的值
            byte[] bytes=zookeeper.getData("/zk-taofut",null,stat);
            System.out.println(new String(bytes));

            //修改节点的值
            zookeeper.setData("/zk-taofut","1".getBytes(),stat.getVersion());

            //得到当前节点的值
            byte[] bytes1=zookeeper.getData("/zk-taofut",null,stat);
            System.out.println(new String(bytes1));

            //删除当前节点
            zookeeper.delete("/zk-taofut",stat.getVersion());

            zookeeper.close();

            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

事件监听

/**
 * 监听事件:Watcher只会监听一次事件,如果需要一直监听,那么要循环了
 */
public class WatcherDemo {
    public static void main(String[] args) {
        try {
            final CountDownLatch countDownLatch=new CountDownLatch(1);
            final ZooKeeper zookeeper=new
                    ZooKeeper("192.168.3.140:2181,192.168.3.141:2181,192.168.3.142:2181", 4000, new Watcher() {
                public void process(WatchedEvent watchedEvent) {
                    System.out.println("默认事件:"+watchedEvent.getType());
                    if(Event.KeeperState.SyncConnected==watchedEvent.getState()){
                        countDownLatch.countDown();
                    }
                }
            });
            countDownLatch.await();

                                //节点路径      值                 ACL(节点的操作权限)       节点的类型,持久化节点
            zookeeper.create("/zk-taofut","0".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

            //绑定事件条件:exists getdata getchildren
            //通过exists绑定事件
            Stat stat=zookeeper.exists("/zk-taofut", new Watcher() {
                public void process(WatchedEvent watchedEvent) {
                    System.out.println(watchedEvent.getType()+"->"+watchedEvent.getPath());
                    //Watcher只能监听一次,所以在这里要做循环
                    try {
                        zookeeper.exists("/zk-taofut",true);//这里的true,表示指代默认的Watcher(以上第17行)
                    } catch (KeeperException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });

            //通过事务-修改来触发监听事件
            stat=zookeeper.setData("/zk-taofut","2".getBytes(),stat.getVersion());

            Thread.sleep(1000);

            zookeeper.delete("/zk-taofut",stat.getVersion());

            System.in.read();


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Curator的使用

节点特性

/**
 * zookeeper节点特性
 */
public class CuratorDemo {

    public static void main(String[] args) throws Exception {
        CuratorFramework curatorFramework= CuratorFrameworkFactory.
                builder().connectString("192.168.3.140:2181,192.168.3.141:2181,192.168.3.142:2181").
                sessionTimeoutMs(4000).retryPolicy(new
                ExponentialBackoffRetry(1000,3)).
                namespace("curator").build();
        curatorFramework.start();

        //创建
        //结果:/curator/taofut/node1
        //原生的zk API中必须逐层创建,也就是说必须存在父节点才能创建子节点
        curatorFramework.create().creatingParentContainersIfNeeded().
                withMode(CreateMode.PERSISTENT).forPath("/taofut/node1","1".getBytes());

        //修改
        Stat stat=new Stat();
        curatorFramework.getData().storingStatIn(stat).forPath("/taofut/node1");

        curatorFramework.setData().withVersion(stat.getVersion()).
                forPath("/taofut/node1","xx".getBytes());

        //删除
        curatorFramework.delete().deletingChildrenIfNeeded().forPath("/taofut/node1");

        curatorFramework.close();

    }
}

事件监听

/**
 * 事件监听
 * PathChildCache 监听一个节点下,子节点的创建、删除、更新
 * NodeCache 监听一个节点的创建和更新
 * TreeCathe 综合PathChildCache和NodeCache的特性
 */
public class CuratorWatcherDemo {

    public static void main(String[] args) throws Exception {
        CuratorFramework curatorFramework= CuratorFrameworkFactory.
                builder().connectString("192.168.3.140:2181,192.168.3.141:2181,192.168.3.142:2181").
                sessionTimeoutMs(4000).retryPolicy(new
                ExponentialBackoffRetry(1000,3)).
                namespace("curator").build();
        curatorFramework.start();
        //监听/taofut节点下的子节点
//        addListenerWithPathChildCache(curatorFramework,"/taofut");
        //监听/taofut节点
//        addListenerWithNodeCache(curatorFramework,"/taofut");
        //监听/taofut节点及子节点
        addListenerWithTreeCache(curatorFramework,"/taofut");
        System.in.read();//进程停留
    }

    /**
     * PathChildCache 监听一个节点下,子节点的创建、删除、更新
     * @param curatorFramework
     * @param path
     * @throws Exception
     */
    public static void addListenerWithPathChildCache(CuratorFramework curatorFramework,String path) throws Exception {
        final PathChildrenCache pathChildrenCache=new PathChildrenCache(curatorFramework,path,true);
        PathChildrenCacheListener pathChildrenCacheListener=new PathChildrenCacheListener() {
            public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
                System.out.println("收到事件:"+pathChildrenCacheEvent.getData().getPath());
            }
        };
        pathChildrenCache.getListenable().addListener(pathChildrenCacheListener);
        pathChildrenCache.start(PathChildrenCache.StartMode.NORMAL);
    }

    /**
     * NodeCache 监听一个节点的创建和更新
     * @param curatorFramework
     * @param path
     * @throws Exception
     */
    public static void addListenerWithNodeCache(CuratorFramework curatorFramework,String path) throws Exception {
        final NodeCache nodeCache=new NodeCache(curatorFramework,path,false);
        NodeCacheListener nodeCacheListener=new NodeCacheListener() {
            public void nodeChanged() throws Exception {
                System.out.println("收到事件:"+nodeCache.getCurrentData().getPath());
            }
        };
        nodeCache.getListenable().addListener(nodeCacheListener);
        nodeCache.start();
    }

    /**
     * TreeCathe 综合PathChildCache和NodeCache的特性
     * @param curatorFramework
     * @param path
     * @throws Exception
     */
    public static void addListenerWithTreeCache(CuratorFramework curatorFramework,String path) throws Exception {
        final TreeCache treeCache=new TreeCache(curatorFramework,path);
        TreeCacheListener treeCacheListener=new TreeCacheListener() {
            public void childEvent(CuratorFramework curatorFramework, TreeCacheEvent treeCacheEvent) throws Exception {
                System.out.println("收到事件:"+treeCacheEvent.getType()+"->"+treeCacheEvent.getData().getPath());
            }
        };
        treeCache.getListenable().addListener(treeCacheListener);
        treeCache.start();
    }

}

猜你喜欢

转载自blog.csdn.net/fu123123fu/article/details/81460052