zookeeper 自动配置更新

reactive 模式监听节点,修改后立即感知,注意zk的watch 和不同操作callBack函数之间的区别

/**
 * @author haowq 2021/4/7 9:46
 */
public class WatcherCallBack implements Watcher, AsyncCallback.StatCallback, AsyncCallback.DataCallback {
    private ZooKeeper zk;
    private CountDownLatch latch = new CountDownLatch(1);
    private MyConfig myConfig;
    //Getter   Setter

    public void await() {
        //判断节点是否存在,然后回调public void processResult(int rc, String path, Object ctx, Stat stat)
        zk.exists("/appConf", this, this, "AsyncCallback.StatCallback");
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //Wathcer process
    public void process(WatchedEvent event) {
        switch (event.getType()) {
            case None:
                break;
            case NodeCreated:
                zk.getData("/appConf", this, this, "AsyncCallback.DataCallback");
                break;
            case NodeDeleted:
                //容忍性
                myConfig.setContent("");
                latch = new CountDownLatch(1);
                break;
            case NodeDataChanged:
                zk.getData("/appConf", this, this, "AsyncCallback.DataCallback");
                break;
            case NodeChildrenChanged:
                break;
        }
    }

    //AsyncCallback.StatCallback
    public void processResult(int rc, String path, Object ctx, Stat stat) {
        System.out.println(rc);
        System.out.println(path);
        System.out.println(ctx.toString());
        if (stat != null) {
            zk.getData("/appConf", this, this, "AsyncCallback.DataCallback");
        }
    }


    //AAsyncCallback.DataCallback
    public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
        if (data != null) {
            myConfig.setContent(new String(data));
            //放行
            latch.countDown();
        }
    }
}

你可能感兴趣的:(zookeeper 自动配置更新)