0


【Nacos】@NacosValue的使用与原理

在这里插入图片描述

在SpringCloud工程中,可以使用@RefreshScope+@Value实现配置文件内容变更后的动态刷新。

在SpringBoot工程中,可以使用@NacosValue来实现配置文件内容变更后的动态刷新。

@NacosValue的使用

引入依赖:

<dependency><groupId>com.alibaba.boot</groupId><artifactId>nacos-config-spring-boot-starter</artifactId><version>0.2.12</version></dependency>

配置文件增加配置:

nacos:
  config:
    server-addr: 127.0.0.1:8848
    bootstrap:
      enable: true
      log:
        enable: true
    data-id: order-service
    type: yaml
    auto-refresh: true# 开启自动刷新

@NacosValue的例子:

packagecom.morris.order.controller;importcom.alibaba.nacos.api.config.annotation.NacosValue;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("order")publicclassNacosValueController{@NacosValue(value ="${user.age}", autoRefreshed =true)privateInteger age2;@GetMapping("age2")publicIntegergetAge2(){return age2;}}

注意在SpringCloud项目中不能使用@NacosValue注解,虽然这个注解存在,但是其源码的实现不存在。

@NacosValue源码分析

NacosConfigEnvironmentProcessor

NacosConfigEnvironmentProcessor实现了EnvironmentPostProcessor,会在SpringBoot项目启动时调用postProcessEnvironment()方法,去Nacos配置中心拉取配置。

需要在配置文件中开启预加载

nacos.config.bootstrap.enable=true

com.alibaba.boot.nacos.config.autoconfigure.NacosConfigEnvironmentProcessor#postProcessEnvironment

publicvoidpostProcessEnvironment(ConfigurableEnvironment environment,SpringApplication application){
    application.addInitializers(newNacosConfigApplicationContextInitializer(this));
    nacosConfigProperties =NacosConfigPropertiesUtils.buildNacosConfigProperties(environment);if(enable()){// nacos.config.bootstrap.enable=trueSystem.out.println("[Nacos Config Boot] : The preload log configuration is enabled");loadConfig(environment);NacosConfigLoader nacosConfigLoader =NacosConfigLoaderFactory.getSingleton(nacosConfigProperties, environment, builder);LogAutoFreshProcess.build(environment, nacosConfigProperties, nacosConfigLoader, builder).process();}}

com.alibaba.boot.nacos.config.autoconfigure.NacosConfigEnvironmentProcessor#loadConfig

privatevoidloadConfig(ConfigurableEnvironment environment){NacosConfigLoader configLoader =newNacosConfigLoader(nacosConfigProperties,
                                                           environment, builder);
    configLoader.loadConfig();// set defer NacosPropertySource
    deferPropertySources.addAll(configLoader.getNacosPropertySources());}

从配置中心拉取配置加入到Environment。
com.alibaba.boot.nacos.config.util.NacosConfigLoader#loadConfig

publicvoidloadConfig(){MutablePropertySources mutablePropertySources = environment.getPropertySources();List<NacosPropertySource> sources =reqGlobalNacosConfig(globalProperties,
                                                             nacosConfigProperties.getType());for(NacosConfigProperties.Config config : nacosConfigProperties.getExtConfig()){List<NacosPropertySource> elements =reqSubNacosConfig(config,
                                                               globalProperties, config.getType());
        sources.addAll(elements);}if(nacosConfigProperties.isRemoteFirst()){// 默认为false,默认本地的配置优先级高for(ListIterator<NacosPropertySource> itr = sources.listIterator(sources.size()); itr.hasPrevious();){
            mutablePropertySources.addAfter(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, itr.previous());}}else{for(NacosPropertySource propertySource : sources){
            mutablePropertySources.addLast(propertySource);}}}

NacosConfigApplicationContextInitializer

NacosConfigApplicationContextInitializer注册负责监听Nacos配置,实现自动刷新配置

com.alibaba.boot.nacos.config.autoconfigure.NacosConfigApplicationContextInitializer#initialize

publicvoidinitialize(ConfigurableApplicationContext context){
    singleton.setApplicationContext(context);
    environment = context.getEnvironment();
    nacosConfigProperties =NacosConfigPropertiesUtils.buildNacosConfigProperties(environment);finalNacosConfigLoader configLoader =NacosConfigLoaderFactory.getSingleton(
        nacosConfigProperties, environment, builder);if(!enable()){
        logger.info("[Nacos Config Boot] : The preload configuration is not enabled");}else{// If it opens the log level loading directly will cache// DeferNacosPropertySource releaseif(processor.enable()){// nacos.config.bootstrap.enable=true
            processor.publishDeferService(context);// 添加监听器
            configLoader
                .addListenerIfAutoRefreshed(processor.getDeferPropertySources());}else{
            configLoader.loadConfig();
            configLoader.addListenerIfAutoRefreshed();}}finalConfigurableListableBeanFactory factory = context.getBeanFactory();if(!factory
        .containsSingleton(NacosBeanUtils.GLOBAL_NACOS_PROPERTIES_BEAN_NAME)){
        factory.registerSingleton(NacosBeanUtils.GLOBAL_NACOS_PROPERTIES_BEAN_NAME,
                                  configLoader.getGlobalProperties());}}

遍历所有的Nacos配置文件,每个配置文件都添加一个监听器。
com.alibaba.boot.nacos.config.util.NacosConfigLoader#addListenerIfAutoRefreshed(java.util.List<com.alibaba.boot.nacos.config.util.NacosConfigLoader.DeferNacosPropertySource>)

publicvoidaddListenerIfAutoRefreshed(finalList<DeferNacosPropertySource> deferNacosPropertySources){for(DeferNacosPropertySource deferNacosPropertySource : deferNacosPropertySources){NacosPropertySourcePostProcessor.addListenerIfAutoRefreshed(
            deferNacosPropertySource.getNacosPropertySource(),
            deferNacosPropertySource.getProperties(),
            deferNacosPropertySource.getEnvironment());}}

要实现配置的自动刷新,需要在配置文件中开启

nacos.config.auto-refresh=true


com.alibaba.nacos.spring.core.env.NacosPropertySourcePostProcessor#addListenerIfAutoRefreshed

publicstaticvoidaddListenerIfAutoRefreshed(finalNacosPropertySource nacosPropertySource,finalProperties properties,finalConfigurableEnvironment environment){// nacos.config.auto-refresh=trueif(!nacosPropertySource.isAutoRefreshed()){// Disable Auto-Refreshedreturn;}finalString dataId = nacosPropertySource.getDataId();finalString groupId = nacosPropertySource.getGroupId();finalString type = nacosPropertySource.getType();finalNacosServiceFactory nacosServiceFactory =getNacosServiceFactoryBean(
        beanFactory);try{ConfigService configService = nacosServiceFactory
            .createConfigService(properties);Listener listener =newAbstractListener(){@OverridepublicvoidreceiveConfigInfo(String config){String name = nacosPropertySource.getName();NacosPropertySource newNacosPropertySource =newNacosPropertySource(
                    dataId, groupId, name, config, type);
                newNacosPropertySource.copy(nacosPropertySource);MutablePropertySources propertySources = environment
                    .getPropertySources();// replace NacosPropertySource// 监听事件的处理,直接替换Environment中的配置
                propertySources.replace(name, newNacosPropertySource);}};if(configService instanceofEventPublishingConfigService){// 通过EventPublishingConfigService进行代理((EventPublishingConfigService) configService).addListener(dataId,
                                                                       groupId, type, listener);}else{
            configService.addListener(dataId, groupId, listener);}}catch(NacosException e){thrownewRuntimeException("ConfigService can't add Listener with properties : "+ properties,
            e);}}

通过EventPublishingConfigService添加监听器,里面对监听器做了一层包装。
com.alibaba.nacos.spring.context.event.config.EventPublishingConfigService#addListener(java.lang.String, java.lang.String, java.lang.String, com.alibaba.nacos.api.config.listener.Listener)

publicvoidaddListener(String dataId,String group,String type,Listener listener)throwsNacosException{Listener listenerAdapter =newDelegatingEventPublishingListener(configService,
                                                                     dataId, group, type, applicationEventPublisher, executor, listener);addListener(dataId, group, listenerAdapter);}

当配置中心的配置变更后,首先会回调DelegatingEventPublishingListener的receiveConfigInfo(),这里会调用被代理的监听器的receiveConfigInfo(),还会发布NacosConfigReceivedEvent事件。
com.alibaba.nacos.spring.context.event.config.DelegatingEventPublishingListener#receiveConfigInfo

publicvoidreceiveConfigInfo(String content){// 调用被代理的监听器的receiveConfigInfo()onReceived(content);// 发布NacosConfigReceivedEvent事件publishEvent(content);}privatevoidpublishEvent(String content){NacosConfigReceivedEvent event =newNacosConfigReceivedEvent(configService,
                                                                  dataId, groupId, content, configType);
    applicationEventPublisher.publishEvent(event);}privatevoidonReceived(String content){
    delegate.receiveConfigInfo(content);}

NacosValueAnnotationBeanPostProcessor

postProcessPropertyValues()

NacosValueAnnotationBeanPostProcessor实现了InstantiationAwareBeanPostProcessorAdapter,其postProcessBeforeInitialization()方法会在Bean实例化之后和初始化之前执行,对Bean上加了@NacosValue注解的属性进行设置。

com.alibaba.spring.beans.factory.annotation.AbstractAnnotationBeanPostProcessor#postProcessPropertyValues

publicPropertyValuespostProcessPropertyValues(PropertyValues pvs,PropertyDescriptor[] pds,Object bean,String beanName)throwsBeanCreationException{// 查找@NacosVaLue注解的属性和方法InjectionMetadata metadata =this.findInjectionMetadata(beanName, bean.getClass(), pvs);try{// 为属性设置值
        metadata.inject(bean, beanName, pvs);return pvs;}catch(BeanCreationException var7){throw var7;}catch(Throwable var8){thrownewBeanCreationException(beanName,"Injection of @"+this.getAnnotationType().getSimpleName()+" dependencies is failed", var8);}}

postProcessBeforeInitialization()

NacosValueAnnotationBeanPostProcessor实现了BeanPostProcessor,其postProcessBeforeInitialization()方法会在Bean实例化之后和初始化之前执行,主要负责收集带有@NacosValue注解且需要自动刷新的属性。

如果属性需要自动刷新,需要设置@NacosValue的autoRefreshed为true。

com.alibaba.nacos.spring.context.annotation.config.NacosValueAnnotationBeanPostProcessor#postProcessBeforeInitialization

publicObjectpostProcessBeforeInitialization(Object bean,finalString beanName)throwsBeansException{// 对Bean所有的属性进行处理doWithFields(bean, beanName);// 对Bean所有的方法进行处理doWithMethods(bean, beanName);returnsuper.postProcessBeforeInitialization(bean, beanName);}privatevoiddoWithFields(finalObject bean,finalString beanName){ReflectionUtils.doWithFields(bean.getClass(),newReflectionUtils.FieldCallback(){@OverridepublicvoiddoWith(Field field)throwsIllegalArgumentException{NacosValue annotation =getAnnotation(field,NacosValue.class);doWithAnnotation(beanName, bean, annotation, field.getModifiers(),null, field);}});}privatevoiddoWithAnnotation(String beanName,Object bean,NacosValue annotation,int modifiers,Method method,Field field){if(annotation !=null){if(Modifier.isStatic(modifiers)){return;}if(annotation.autoRefreshed()){String placeholder =resolvePlaceholder(annotation.value());if(placeholder ==null){return;}NacosValueTarget nacosValueTarget =newNacosValueTarget(bean, beanName,
                                                                     method, field, annotation.value());// 将带有@NacosValue注解的属性加入到一个Map中put2ListMap(placeholderNacosValueTargetMap, placeholder,
                        nacosValueTarget);}}}

监听NacosConfigReceivedEvent

收到NacosConfigReceivedEvent事件时,通过反射调用上面收集好的属性和方法从而实现自动刷新。

com.alibaba.nacos.spring.context.annotation.config.NacosValueAnnotationBeanPostProcessor#onApplicationEvent

publicvoidonApplicationEvent(NacosConfigReceivedEvent event){// In to this event receiver, the environment has been updated the// latest configuration information, pull directly from the environment// fix issue #142for(Map.Entry<String,List<NacosValueTarget>> entry : placeholderNacosValueTargetMap
         .entrySet()){String key = environment.resolvePlaceholders(entry.getKey());String newValue = environment.getProperty(key);if(newValue ==null){continue;}List<NacosValueTarget> beanPropertyList = entry.getValue();for(NacosValueTarget target : beanPropertyList){String md5String =MD5Utils.md5Hex(newValue,"UTF-8");boolean isUpdate =!target.lastMD5.equals(md5String);if(isUpdate){
                target.updateLastMD5(md5String);Object evaluatedValue =resolveNotifyValue(target.nacosValueExpr, key, newValue);if(target.method ==null){setField(target, evaluatedValue);}else{setMethod(target, evaluatedValue);}}}}}

本文转载自: https://blog.csdn.net/u022812849/article/details/129261137
版权归原作者 morris131 所有, 如有侵权,请联系我们删除。

“【Nacos】@NacosValue的使用与原理”的评论:

还没有评论