Java 对 Zookeeper 的简单使用

依赖

<dependency>
    <groupId>org.apache.zookeeper</groupId>
    <artifactId>zookeeper</artifactId>
    <version>3.6.3</version>
</dependency>

添加path并且添加数据

public void createPathAndAddData() throws Exception {
    /**
     * 连接地址多个,分隔
     * 连接时间
     * 回调方法
     */
    ZooKeeper zooKeeper = new ZooKeeper("127.0.0.1:2181"
            , 30000
            , new Watcher() {
        @Override
        public void process(WatchedEvent watchedEvent) {
            System.out.println("------new ZooKeeper-------");
            Event.KeeperState state = watchedEvent.getState();
            Event.EventType type = watchedEvent.getType();
            String path = watchedEvent.getPath();
            System.out.println("state: " + state + ", type: " + type + ", path: " + path);
        }
    });
    String path = "/oooo";
    String data = "testData";
    //创建path并添加数据,连接结束会删除
    String resPath = zooKeeper.create(path, data.getBytes()
            , ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
    System.out.println(resPath);
        Thread.sleep(10*10000);
}

获取数据或重新set数据

public void getDataAndSetData() throws Exception {
    /**
     * 连接地址多个,分隔
     * 连接时间
     * 回调方法
     */
    ZooKeeper zooKeeper = new ZooKeeper("127.0.0.1:2181"
            , 30000
            , new Watcher() {
        @Override
        public void process(WatchedEvent watchedEvent) {
            System.out.println("------new ZooKeeper-------");
            Event.KeeperState state = watchedEvent.getState();
            Event.EventType type = watchedEvent.getType();
            String path = watchedEvent.getPath();
            System.out.println("state: " + state + ", type: " + type + ", path: " + path);
        }
    });
    String path = "/xxoo";
    Stat stat = new Stat();
    //同步获取数据
    byte[] data = zooKeeper.getData(path, new Watcher() {
        @Override
        public void process(WatchedEvent watchedEvent) {
            System.out.println("------getData-------");
            Event.KeeperState state = watchedEvent.getState();
            Event.EventType type = watchedEvent.getType();
            String path = watchedEvent.getPath();
            System.out.println("state: " + state + ", type: " + type + ", path: " + path);
        }
    }, stat);
    String s = data == null ? null : new String(data);
    System.out.println(s);
    String newData = "Data1111";
    //设置数据
    zooKeeper.setData(path, newData.getBytes(), 1);
    //异步获取数据
    zooKeeper.getData(path, false, new AsyncCallback.DataCallback() {
        @Override
        public void processResult(int i, String s, Object o, byte[] bytes, Stat stat) {
            System.out.println("异步回调");
            String sss = bytes == null ? null : new String(bytes);
            System.out.println(sss);
        }
    }, "obj");
}
posted @ 2022-03-07 18:03  叕叕666  阅读(218)  评论(0)    收藏  举报