小记一下Zookeeper配置中心的部分原理

记录一下,这里其实很类似nacos的@Value,注解,可以结合去理解。

java 复制代码
@Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> beanClass = bean.getClass();
        Field[] fields = beanClass.getDeclaredFields();
        for (Field field : fields) {
            if (!field.isAnnotationPresent(DCCValue.class)) {
                continue;
            }

            DCCValue dccValue = field.getAnnotation(DCCValue.class);

            String value = dccValue.value();
            if (StringUtils.isBlank(value)) {
                throw new RuntimeException(field.getName() + " @DCCValue is not config value config case 「isSwitch/isSwitch:1」");
            }

            String[] splits = value.split(":");
            String key = splits[0];
            String defaultValue = splits.length == 2 ? splits[1] : null;

            try {
                // 判断当前节点是否存在,不存在则创建出 Zookeeper 节点
                String keyPath = BASE_CONFIG_PATH_CONFIG.concat("/").concat(key);
                if (null == client.checkExists().forPath(keyPath)) {
                    client.create().creatingParentsIfNeeded().forPath(keyPath);
                    if (StringUtils.isNotBlank(defaultValue)) {
                        field.setAccessible(true);
                        field.set(bean, defaultValue);
                        field.setAccessible(false);
                    }
                    log.info("DCC 节点监听 创建节点 {}", keyPath);
                } else {
                    String configValue = new String(client.getData().forPath(keyPath));
                    if (StringUtils.isNotBlank(configValue)) {
                        field.setAccessible(true);
                        field.set(bean, configValue);
                        field.setAccessible(false);
                        log.info("DCC 节点监听 设置配置 {} {} {}", keyPath, field.getName(), configValue);
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            dccObjGroup.put(BASE_CONFIG_PATH_CONFIG.concat("/").concat(key), bean);
        }
        return bean;
    }

解答疑惑:

  1. 平时使用配置中心时,注解标记后能读取到配置的原因

  2. 注解中设置了默认值,当读取配置中心为空时,使用该默认值的原因

相关推荐
昵称为空C2 分钟前
SpringBoot接口限流的常用方案
服务器·spring boot
hrrrrb25 分钟前
【Java Web 快速入门】十一、Spring Boot 原理
java·前端·spring boot
Java微观世界36 分钟前
Object核心类深度剖析
java·后端
MrSYJ40 分钟前
为什么HttpSecurity会初始化创建两次
java·后端·程序员
hinotoyk1 小时前
TimeUnit源码分享
java
Peter_Deng.1 小时前
Linux 下基于 TCP 的 C 语言客户端/服务器通信详解(三个示例逐步进阶)
服务器·c语言·网络
花小璇学linux1 小时前
imx6ull-驱动开发篇24——Linux 中断API函数
linux·驱动开发·嵌入式软件
林开落L1 小时前
库制作与原理(下)
linux·开发语言·centos·库制作与原理
AAA修煤气灶刘哥2 小时前
Java+AI 驱动的体检报告智能解析:从 PDF 提取到数据落地全指南
java·人工智能·后端
wxy3192 小时前
嵌入式LINUX——————TCP并发服务器
java·linux·网络