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

相关推荐
Key~美好的每一天9 分钟前
一文了解JVM的垃圾回收
java·jvm
tan180°10 分钟前
版本控制器Git(4)
linux·c++·git·后端·vim
程序员小刚32 分钟前
基于springboot + vue 的实验室(预约)管理系统
vue.js·spring boot·后端
IT 古月方源35 分钟前
linux centos 忘记root密码拯救
linux·运维·centos
程序员小刚35 分钟前
基于SpringBoot + Vue 的校园论坛系统
vue.js·spring boot·后端
By北阳36 分钟前
Go语言 vs Java语言:核心差异与适用场景解析
java·开发语言·golang
J总裁的小芒果1 小时前
java项目发送短信--腾讯云
java·python·腾讯云
wenbin_java1 小时前
设计模式之桥接模式:原理、实现与应用
java·设计模式·桥接模式
孫治AllenSun1 小时前
【Synchronized】不同的使用场景和案例
java·开发语言·jvm
计算机学长felix1 小时前
基于SpringBoot的“校园周边美食探索及分享平台”的设计与实现(源码+数据库+文档+PPT)
spring boot·毕业设计