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

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

创新互联公司专注于企业全网整合营销推广、网站重做改版、河口网站定制设计、自适应品牌网站建设、H5响应式网站商城开发、集团公司官网建设、成都外贸网站建设、高端网站制作、响应式网页设计等建站业务,价格优惠性价比高,为河口等各大城市提供网站开发制作服务。

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 oldConfig = Maps.newConcurrentMap();
    private static ConcurrentMap 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 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中怎么通过监听读取配置信息了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注创新互联行业资讯频道。


新闻标题:zk中怎么通过监听读取配置信息
标题URL:http://hbruida.cn/article/gecpgo.html