看守者从Zookeeper中检索节点数据 [英] Watcher for retrieving node data from zookeeper

查看:50
本文介绍了看守者从Zookeeper中检索节点数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一些方法,可以在没有观察者的情况下从zookeeper节点检索数据. zookeeper.getData(nodePath,false,null);

I have written methods to retrieve data from zookeeper node without watcher. zookeeper.getData(nodePath, false, null);

上面的方法调用将返回节点中的数据.

The above method call will return the data in the node.

现在,我想从节点中获取数据,并且稍后当节点中发生更新时,我希望返回更新后的数据.

Now I want to fetch data from the node and later when an update occurs in the node, I want the updated data to be returned.

这是与Zookeeper进行交互的来源

This is the source to interact with zookeeper

public class ZooKeeperOperations {

public enum ZooKeeperResult {
    SUCCESS, NO_NODE_EXISTS, NODE_ALREADY_EXISTS, BAD_VERSION, CONNECTION_LOSS, NODE_NOT_EMPTY, FAILURE;
}

static ZooKeeperOperations instance = new ZooKeeperOperations();

private ZooKeeperOperations() {
}

public static ZooKeeperOperations getInstance() {
    return instance;
}

private static ZooKeeper zk;
private static final String HOST = "localhost"; // No I18N
private static final String APPLICATION_GROUP_NAME = "AppName"; // No I18N

public ZooKeeper connect(String host) throws IOException, InterruptedException {

    zk = new ZooKeeper(host, 5000,new Watcher() {

          public void process(WatchedEvent we) {

          }
       });

    return zk;
}

// Method to disconnect from zookeeper server
public void close() {
    try {
        zk.close();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

public static Stat znode_exists(String path) {
    try {
        return zk.exists(getAppPath(path), true);
    } catch (KeeperException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return null;
}

private static String getAppPath(String path) {
    return "/" + APPLICATION_GROUP_NAME + "/" + path;
}

public Object[] getNodeData(String path, boolean watch, Stat stat) {
    try {
        String nodePath = getAppPath(path);
        byte[] propertyData = this.connect(HOST).getData(nodePath, watch, stat);

        TBLogger.logMessage(Level.SEVERE, TBoxIAMUtil.getUserAPI().getCurrentUserZuid(), CLASSNAME, "getNodeData",
                new Object[] { new String(propertyData) }, null);

        return new Object[] { ZooKeeperResult.SUCCESS, propertyData };
    } catch (ConnectionLossException e) {
        return new Object[] { ZooKeeperResult.CONNECTION_LOSS };
    } catch (NoNodeException e) {
        return new Object[] { ZooKeeperResult.NO_NODE_EXISTS };
    } catch (Exception e) {
        return new Object[] { ZooKeeperResult.FAILURE };
    } finally {
        this.close();
    }

}

}

有人可以帮我吗,我是Zookeeper的新手:(

推荐答案

使用 Curator .

    String connStr = "localhost:2181";
    CuratorFramework client;
    client = CuratorFrameworkFactory
            .builder()
            .connectString(connStr)
            .sessionTimeoutMs(15000)
            .connectionTimeoutMs(15000)
            .retryPolicy(new ExponentialBackoffRetry(1000, 3))
            .build();
    client.start();

    String path = "/zk-path-you-might-care";

    try {
        byte[] dataBytes = client.getData().forPath(path);
        System.out.println(new String(dataBytes));
    } catch (KeeperException.NoNodeException e) {
        client.create().forPath(path);
    }

    ExecutorService pool = Executors.newFixedThreadPool(5);
    TreeCache treeCache = new TreeCache(client, path);
    treeCache.getListenable().addListener((curatorFramework, event) -> {
        ChildData data = event.getData();
        if (data == null) {
            System.out.println("No data in tree event[" + event + "]");
        } else {
            System.out.println("Receive tree event: "
                    + "type=[" + event.getType() + "]"
                    + ", path=[" + data.getPath() + "]"
                    + ", data=[" + new String(data.getData()) + "]"
                    + ", stat=[" + data.getStat().toString().trim() + "]");
        }
    }, pool);
    treeCache.start();

    while (true) {
        Thread.sleep(100000);
        System.out.println("sleep infinite..");
    }

这篇关于看守者从Zookeeper中检索节点数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆