温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

zk中怎么通过监听读取配置信息

发布时间:2021-06-21 14:54:31 来源:亿速云 阅读:162 作者:Leah 栏目:大数据

这期内容当中小编将会给大家带来有关zk中怎么通过监听读取配置信息,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class ZkClientWatcher implements Watcher {

    private static final String CONNECT_ADDRESS = "10.10.136.114:2181,10.10.136.114:2182,10.10.136.114:2183";
    private static final int SESSION_TIMEOUT = 2000;
    public static final int MAX = 3;
    private static String CONFIG_PATH = "/application-config";
    private static ZooKeeper zk;
    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    private static ConcurrentMap<String, String> oldConfig = Maps.newConcurrentMap();
    private static ConcurrentMap<String, String> newConfig = Maps.newConcurrentMap();

    private static AtomicInteger count = new AtomicInteger(1);

    public void createConnection(String connectAddres, int sessionTimeOut) throws InterruptedException {
        try {
            zk = new ZooKeeper(connectAddres, sessionTimeOut, this);
            log.info("zk connecting...");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
    }

    public boolean createPath(String path, String data) {
        try {
            if (null == zk.exists(path, true)) {
                zk.create(path, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
                log.info("node create success");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    @Override
    public void process(WatchedEvent event) {

        Event.KeeperState keeperState = event.getState();
        Event.EventType eventType = event.getType();
        String path = event.getPath();
        log.info("process:{},keeperState:{},eventType:{},path:{}", keeperState, eventType, path);
        if (Event.KeeperState.SyncConnected == keeperState) {

            if (Event.EventType.None == eventType) {
                log.info("now status is None");

            } else if (Event.EventType.NodeCreated == eventType) {
                log.info("now status is nodeCreated,path:{}", path);
            } else if (Event.EventType.NodeDataChanged == eventType) {
                log.info("now status is nodedataChanged:{}", path);
                try {
                    newConfig = JSON.parseObject(zk.getData(path, true, new Stat()), ConcurrentMap.class);
                    log.info("newConfig is {}", newConfig);
                    count.getAndIncrement();
                    if (count.get() > MAX) {
                        countDownLatch.countDown();
                    }
                } catch (Exception e) {
                    log.error("get data from zk occur exception", e);
                }

            } else if (Event.EventType.NodeDeleted == eventType) {
                log.info("now status is node deleted:{}", path);
            }
        }
    }

    public static void main(String[] args) throws Exception {

        ZkClientWatcher watcher = new ZkClientWatcher();
        watcher.createConnection(CONNECT_ADDRESS, SESSION_TIMEOUT);
        createPathAndInitData(watcher);
        getOldConfig();
        countDownLatch.await();
        log.info("test complete!config has changed 3 times");
    }

    /**
     * 第一次获取配置信息
     *
     * @throws Exception
     */
    private static void getOldConfig() throws Exception {
        oldConfig = JSON.parseObject(zk.getData(CONFIG_PATH, true, new Stat()), ConcurrentMap.class);
        log.info("oldConfig is {}", oldConfig);
    }

    /**
     * 创建path设置初始值
     *
     * @param watcher
     */
    private static void createPathAndInitData(ZkClientWatcher watcher) {
        Map<String, String> maps = Maps.newConcurrentMap();
        maps.put("spring.data.status.start", "true");
        maps.put("switch", "on");
        maps.put("startTime", "2019-10-24 12:00:00");
        maps.put("coder", "1024");
        watcher.createPath(CONFIG_PATH, JSON.toJSONString(maps));
    }
}

上述就是小编为大家分享的zk中怎么通过监听读取配置信息了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

zk
AI