溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

zk中怎么通過監(jiān)聽讀取配置信息

發(fā)布時(shí)間:2021-06-21 14:54:31 來源:億速云 閱讀:155 作者:Leah 欄目:大數(shù)據(jù)

這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)碛嘘P(guān)zk中怎么通過監(jiān)聽讀取配置信息,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

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);
    }

    /**
     * 創(chuàng)建path設(shè)置初始值
     *
     * @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中怎么通過監(jiān)聽讀取配置信息了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

zk
AI