• Zookeeper:实现“通知协调”的 Demo


    应用配置集中到节点上,应用启动时主动获取,并在节点上注册一个 watcher,每次配置更新都会通知到应用。数据发布/订阅(Publish/Subscribe)系统,即所谓的配置中心,顾名思义就是发布者将数据发布到 ZooKeeper 的一个或一系列节点上,供订阅者进行数据订阅,进而达到动态获取数据的目的,实现配置信息的集中式管理和数据的动态更新。

    本篇内容包括:Demo 概述、代码实现、测试结果



    一、Demo 概述

    1、关于 zookeeper “通知协调”

    应用配置集中到节点上,应用启动时主动获取,并在节点上注册一个 watcher,每次配置更新都会通知到应用。

    数据发布/订阅(Publish/Subscribe)系统,即所谓的配置中心,顾名思义就是发布者将数据发布到 ZooKeeper 的一个或一系列节点上,供订阅者进行数据订阅,进而达到动态获取数据的目的,实现配置信息的集中式管理和数据的动态更新。

    2、Demo 设计

    采用发布/订阅模式将配置信息发布到 Zookeeper 节点上,供订阅者动态获取数据:

    Zookeeper订阅发布Demo
    1. 首先需要启动 Zookeeper 服务,规划集群配置信息存放的节点 /config;
    2. 然后通过 ConfigWatcher 类更新 /config 节点注册监视器 watcher,监控集群配置信息变化;
    3. 最后通过 ConfigUpdater 类不断更新 /config 节点配置信息,从而模拟实现集群配置信息订阅发布效果。
    3、Demo 前提

    参考:Mac通过Docker安装Zookeeper集群


    二、代码实现

    1、引用 Maven 依赖
            
            <dependency>
                <groupId>org.apache.zookeepergroupId>
                <artifactId>zookeeperartifactId>
                <version>3.7.0version>
            dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    2、ConnectionWatcher 类创建 Zookeeper 连接
    import java.io.IOException;
    import java.util.concurrent.CountDownLatch;
    
    import org.apache.zookeeper.WatchedEvent;
    import org.apache.zookeeper.Watcher;
    import org.apache.zookeeper.ZooKeeper;
    
    public class ConnectionWatcher implements Watcher {
    
        private final CountDownLatch connectedSignal = new CountDownLatch(1);
        private static final int SESSION_TIMEOUT = 5000;
        protected ZooKeeper zk;
    
    
        public void connect(String hosts) throws IOException, InterruptedException {
            zk = new ZooKeeper(hosts, SESSION_TIMEOUT, this);
            connectedSignal.await();
        }
    
        @Override
        public void process(WatchedEvent event) {
            if (event.getState() == Event.KeeperState.SyncConnected) {
                connectedSignal.countDown();
            }
        }
    
        public void close() throws InterruptedException {
            zk.close();
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    3、ActiveKeyValueStore 类读写 Zookeeper 数据
    import java.nio.charset.Charset;
    import java.nio.charset.StandardCharsets;
    import java.util.List;
    
    import org.apache.zookeeper.CreateMode;
    import org.apache.zookeeper.KeeperException;
    import org.apache.zookeeper.Watcher;
    import org.apache.zookeeper.ZooDefs;
    import org.apache.zookeeper.data.Stat;
    
    public class ActiveKeyValueStore extends ConnectionWatcher {
    
        private static final Charset CHARSET = StandardCharsets.UTF_8;
    
        /**
         * 读取节点数据
         *
         * @param path  节点地址
         * @param value 数据值
         * @throws InterruptedException 中断异常
         * @throws KeeperException ZooKeeper异常
         */
        public void write(String path, String value) throws InterruptedException, KeeperException {
            Stat stat = zk.exists(path, false);
            if (stat == null) {
                if (value == null) {
                    zk.create(path, null,
                            ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                } else {
                    zk.create(path, value.getBytes(CHARSET),
                            ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                }
    
            } else {
                if (value == null) {
                    zk.setData(path, null, -1);
                } else {
                    zk.setData(path, value.getBytes(CHARSET), -1);
                }
    
            }
        }
    
        /**
         * 读取节点数据
         *
         * @param path 节点地址
         * @param watcher watcher
         * @return 数据值
         * @throws InterruptedException 中断异常
         * @throws KeeperException ZooKeeper异常
         */
        public String read(String path, Watcher watcher) throws InterruptedException, KeeperException {
            /* stat */
            byte[] data = zk.getData(path, watcher, null);
            return new String(data, CHARSET);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    4、ConfigUpdater 类发布数据信息
    import java.io.IOException;
    import java.util.Random;
    import java.util.concurrent.TimeUnit;
    
    import org.apache.zookeeper.KeeperException;
    
    public class ConfigUpdater {
        public static final String PATH = "/configuration";
        private final ActiveKeyValueStore store;
        private final Random random = new Random();
    
        public ConfigUpdater(String hosts) throws IOException, InterruptedException {
            //定义一个类
            store = new ActiveKeyValueStore();
            //连接Zookeeper
            store.connect(hosts);
        }
    
        public void run() throws InterruptedException, KeeperException {
            // noinspection InfiniteLoopStatement
            while (true) {
                String value = random.nextInt(100) + "";
                //向 ZNode 写数据(也可以将xml文件写进去)
                store.write(PATH, value);
                System.out.printf("Set %s to %s\n", PATH, value);
                TimeUnit.SECONDS.sleep(random.nextInt(10));
            }
        }
    
        public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
            String hosts = "localhost:2181";
            ConfigUpdater updater = new ConfigUpdater(hosts);
            updater.run();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    5、ConfigWatcher 类订阅数据信息
    import java.io.IOException;
    
    import org.apache.zookeeper.KeeperException;
    import org.apache.zookeeper.WatchedEvent;
    import org.apache.zookeeper.Watcher;
    
    public class ConfigWatcher implements Watcher {
        private final ActiveKeyValueStore store;
    
        public ConfigWatcher(String hosts) throws InterruptedException, IOException {
            store = new ActiveKeyValueStore();
            //连接Zookeeper
            store.connect(hosts);
        }
    
        public void displayConfig() throws InterruptedException, KeeperException {
            String value = store.read(ConfigUpdater.PATH, this);
            System.out.printf("Read %s as %s\n", ConfigUpdater.PATH, value);
    
        }
    
        @Override
        public void process(WatchedEvent event) {
            System.out.printf("Process incoming event: %s\n", event.toString());
            if (event.getType() == Event.EventType.NodeDataChanged) {
                try {
                    displayConfig();
                } catch (InterruptedException e) {
                    System.err.println("Interrupted. Exiting");
                    Thread.currentThread().interrupt();
                } catch (KeeperException e) {
                    System.err.printf("KeeperException: %s. Exiting.\n", e);
                }
            }
        }
    
        public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
            String hosts = "localhost:2181";
            //创建 watcher
            ConfigWatcher watcher = new ConfigWatcher(hosts);
            //调用 display 方法
            watcher.displayConfig();
            //然后一直处于监控状态
            Thread.sleep(Long.MAX_VALUE);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46

    三、测试结果

    1、ConfigUpdater 打印内容
    Set /configuration to 76
    Set /configuration to 55
    Set /configuration to 13
    ...
    
    • 1
    • 2
    • 3
    • 4
    2、ConfigWatcher 打印内容
    Read /configuration as 76
    Read /configuration as 55
    Read /configuration as 13
    ...
    
    • 1
    • 2
    • 3
    • 4

    通过 ConfigUpdater 发布的信息以及 ConfigWatcher 监控得到的信息可以看出,已经成功模拟实现集群配置信息的订阅发布

  • 相关阅读:
    Java-异常
    cube开源一站式云原生机器学习平台--volcano 多机分布式计算
    WordPress网站更改后台登录地址保姆级图文教程
    【开源】SpringBoot框架开发新能源电池回收系统
    利用Python进行数据分析【送书第六期:文末送书】
    04-继承与多态
    计算机毕业设计(附源码)python智慧社区信息平台
    CHERRY樱桃机械键盘按键
    六大科研工具推荐,外文文献阅读管理全都搞定!
    《Java8实战》读书笔记09:用 Optional 处理值为 null 的情况
  • 原文地址:https://blog.csdn.net/weixin_45187434/article/details/127968530