小记一下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. 注解中设置了默认值,当读取配置中心为空时,使用该默认值的原因

相关推荐
超浪的晨8 分钟前
Java UDP 通信详解:从基础到实战,彻底掌握无连接网络编程
java·开发语言·后端·学习·个人开发
双力臂4041 小时前
Spring Boot 单元测试进阶:JUnit5 + Mock测试与切片测试实战及覆盖率报告生成
java·spring boot·后端·单元测试
心之语歌1 小时前
Spring AI MCP 客户端
人工智能·spring·github
Edingbrugh.南空1 小时前
Aerospike与Redis深度对比:从架构到性能的全方位解析
java·开发语言·spring
van叶~1 小时前
Linux网络-------1.socket编程基础---(TCP-socket)
linux·网络·tcp/ip
风吹落叶花飘荡2 小时前
Ubuntu系统 系统盘和数据盘扩容具体操作
linux·运维·ubuntu
QQ_4376643142 小时前
C++11 右值引用 Lambda 表达式
java·开发语言·c++
永卿0012 小时前
设计模式-迭代器模式
java·设计模式·迭代器模式
誰能久伴不乏2 小时前
Linux如何执行系统调用及高效执行系统调用:深入浅出的解析
java·服务器·前端
zoulingzhi_yjs2 小时前
haproxy配置详解
linux·云原生