最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring Cloud Alibaba Nacos Config加載配置詳解流程

 更新時(shí)間:2022年07月04日 11:03:45   作者:喜歡小蘋果的碼農(nóng)  
這篇文章主要介紹了Spring Cloud Alibaba Nacos Config配置中心實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

1、加載節(jié)點(diǎn)

SpringBoot啟動(dòng)時(shí),會(huì)執(zhí)行這個(gè)方法:SpringApplication#run,這個(gè)方法中會(huì)調(diào)prepareContext來準(zhǔn)備上下文,這個(gè)方法中調(diào)用了applyInitializers方法來執(zhí)行實(shí)現(xiàn)了ApplicationContextInitializer接口的類的initialize方法。其中包括PropertySourceBootstrapConfiguration#initialize 來加載外部的配置。

@Autowired(required = false)
private List<PropertySourceLocator> propertySourceLocators = new ArrayList<>();
public void initialize(ConfigurableApplicationContext applicationContext) {
	...
   for (PropertySourceLocator locator : this.propertySourceLocators) {
       //載入PropertySource
      Collection<PropertySource<?>> source = locator.locateCollection(environment);
      ...
   }
   ...
}
//org.springframework.cloud.bootstrap.config.PropertySourceLocator#locateCollection
default Collection<PropertySource<?>> locateCollection(Environment environment) {
    return locateCollection(this, environment);
}
//org.springframework.cloud.bootstrap.config.PropertySourceLocator#locateCollection
static Collection<PropertySource<?>> locateCollection(PropertySourceLocator locator, Environment environment) {
    //執(zhí)行l(wèi)ocate方法,將PropertySource加載進(jìn)來
    PropertySource<?> propertySource = locator.locate(environment);
    ...
}

這個(gè)類中會(huì)注入實(shí)現(xiàn)了PropertySourceLocator接口的類,在nacos中是NacosPropertySourceLocator。

在initialize方法中會(huì)執(zhí)行NacosPropertySourceLocator的locate方法,將NacosPropertySource加載進(jìn)來。

2、NacosPropertySourceLocator的注冊

NacosPropertySourceLocator在配置類NacosConfigBootstrapConfiguration中注冊。

@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(name = "spring.cloud.nacos.config.enabled", matchIfMissing = true)
public class NacosConfigBootstrapConfiguration {
   @Bean
   @ConditionalOnMissingBean
   public NacosConfigProperties nacosConfigProperties() {
      return new NacosConfigProperties();
   }
   @Bean
   @ConditionalOnMissingBean
   public NacosConfigManager nacosConfigManager(
         NacosConfigProperties nacosConfigProperties) {
      return new NacosConfigManager(nacosConfigProperties);
   }
   @Bean
   public NacosPropertySourceLocator nacosPropertySourceLocator(
         NacosConfigManager nacosConfigManager) {
      return new NacosPropertySourceLocator(nacosConfigManager);
   }
}

在這里會(huì)依次注冊NacosConfigProperties,NacosConfigManager,NacosPropertySourceLocator。

3、加載

//com.alibaba.cloud.nacos.client.NacosPropertySourceLocator#locate
public PropertySource<?> locate(Environment env) {
   nacosConfigProperties.setEnvironment(env);
    //獲取ConfigService
   ConfigService configService = nacosConfigManager.getConfigService();

   if (null == configService) {
      log.warn("no instance of config service found, can't load config from nacos");
      return null;
   }
   long timeout = nacosConfigProperties.getTimeout();
    //構(gòu)建nacosPropertySourceBuilder
   nacosPropertySourceBuilder = new NacosPropertySourceBuilder(configService,
         timeout);
   String name = nacosConfigProperties.getName();
	//獲取dataIdPrefix,一次從prefix,name,spring.application.name中獲取
   String dataIdPrefix = nacosConfigProperties.getPrefix();
   if (StringUtils.isEmpty(dataIdPrefix)) {
      dataIdPrefix = name;
   }
   if (StringUtils.isEmpty(dataIdPrefix)) {
      dataIdPrefix = env.getProperty("spring.application.name");
   }
	//構(gòu)建CompositePropertySource:NACOS
   CompositePropertySource composite = new CompositePropertySource(
         NACOS_PROPERTY_SOURCE_NAME);
	//加載share 配置
   loadSharedConfiguration(composite);
   //加載extention 配置
   loadExtConfiguration(composite);
    //加載application配置
   loadApplicationConfiguration(composite, dataIdPrefix, nacosConfigProperties, env);
   return composite;
}

3.1、加載share

private void loadSharedConfiguration(
      CompositePropertySource compositePropertySource) {
   //獲取share節(jié)點(diǎn)的配置信息
   List<NacosConfigProperties.Config> sharedConfigs = nacosConfigProperties
         .getSharedConfigs();
    //如果不為空,加載
   if (!CollectionUtils.isEmpty(sharedConfigs)) {
      checkConfiguration(sharedConfigs, "shared-configs");
      loadNacosConfiguration(compositePropertySource, sharedConfigs);
   }
}

加載配置,公用方法

//com.alibaba.cloud.nacos.client.NacosPropertySourceLocator#loadNacosConfiguration
private void loadNacosConfiguration(final CompositePropertySource composite,
                                    List<NacosConfigProperties.Config> configs) {
    for (NacosConfigProperties.Config config : configs) {
        loadNacosDataIfPresent(composite, config.getDataId(), config.getGroup(),
                               NacosDataParserHandler.getInstance()
                               .getFileExtension(config.getDataId()),
                               config.isRefresh());
    }
}
//com.alibaba.cloud.nacos.client.NacosPropertySourceLocator#loadNacosDataIfPresent
private void loadNacosDataIfPresent(final CompositePropertySource composite,
      final String dataId, final String group, String fileExtension,
      boolean isRefreshable) {
   if (null == dataId || dataId.trim().length() < 1) {
      return;
   }
   if (null == group || group.trim().length() < 1) {
      return;
   }
    //加載NacosPropertySource,后面也會(huì)用這個(gè)方法
   NacosPropertySource propertySource = this.loadNacosPropertySource(dataId, group,
         fileExtension, isRefreshable);
    //將NacosPropertySource放入第一個(gè)
   this.addFirstPropertySource(composite, propertySource, false);
}

加載NacosPropertySource

//com.alibaba.cloud.nacos.client.NacosPropertySourceLocator#loadNacosPropertySource
private NacosPropertySource loadNacosPropertySource(final String dataId,
      final String group, String fileExtension, boolean isRefreshable) {
   //標(biāo)注@RefreshScope的類的數(shù)量不為0,且不允許自動(dòng)刷新,從緩存加載nacos的配置
    if (NacosContextRefresher.getRefreshCount() != 0) {
      if (!isRefreshable) {
         return NacosPropertySourceRepository.getNacosPropertySource(dataId,
               group);
      }
   }
   return nacosPropertySourceBuilder.build(dataId, group, fileExtension,
         isRefreshable);
}

從緩存中加載

//NacosPropertySourceRepository
private final static ConcurrentHashMap<String, NacosPropertySource> NACOS_PROPERTY_SOURCE_REPOSITORY = new ConcurrentHashMap<>();
public static NacosPropertySource getNacosPropertySource(String dataId,
      String group) {
   return NACOS_PROPERTY_SOURCE_REPOSITORY.get(getMapKey(dataId, group));
}
public static String getMapKey(String dataId, String group) {
   return String.join(NacosConfigProperties.COMMAS, String.valueOf(dataId),
         String.valueOf(group));
}

NacosPropertySourceRepository中緩存了NacosPropertySource

獲取配置并加入緩存

//com.alibaba.cloud.nacos.client.NacosPropertySourceBuilder#build
NacosPropertySource build(String dataId, String group, String fileExtension,
      boolean isRefreshable) {
    //獲取配置
   List<PropertySource<?>> propertySources = loadNacosData(dataId, group,
         fileExtension);
    //包裝成NacosPropertySource
   NacosPropertySource nacosPropertySource = new NacosPropertySource(propertySources,
         group, dataId, new Date(), isRefreshable);
    //加入緩存
   NacosPropertySourceRepository.collectNacosPropertySource(nacosPropertySource);
   return nacosPropertySource;
}
//com.alibaba.cloud.nacos.client.NacosPropertySourceBuilder#loadNacosData
private List<PropertySource<?>> loadNacosData(String dataId, String group,
      String fileExtension) {
   String data = null;
   try {
       //獲取配置
      data = configService.getConfig(dataId, group, timeout);
      if (StringUtils.isEmpty(data)) {
         log.warn(
               "Ignore the empty nacos configuration and get it based on dataId[{}] & group[{}]",
               dataId, group);
         return Collections.emptyList();
      }
      if (log.isDebugEnabled()) {
         log.debug(String.format(
               "Loading nacos data, dataId: '%s', group: '%s', data: %s", dataId,
               group, data));
      }
      return NacosDataParserHandler.getInstance().parseNacosData(dataId, data,
            fileExtension);
   }
   catch (NacosException e) {
      log.error("get data from Nacos error,dataId:{} ", dataId, e);
   }
   catch (Exception e) {
      log.error("parse data from Nacos error,dataId:{},data:{}", dataId, data, e);
   }
   return Collections.emptyList();
}
//com.alibaba.nacos.client.config.NacosConfigService#getConfig
public String getConfig(String dataId, String group, long timeoutMs) throws NacosException {
    return getConfigInner(namespace, dataId, group, timeoutMs);
}
//com.alibaba.nacos.client.config.NacosConfigService#getConfigInner
private String getConfigInner(String tenant, String dataId, String group, long timeoutMs) throws NacosException {
    group = blank2defaultGroup(group);
    ParamUtils.checkKeyParam(dataId, group);
    //聲明響應(yīng)
    ConfigResponse cr = new ConfigResponse();
    //設(shè)置dataId,tenant,group
    cr.setDataId(dataId);
    cr.setTenant(tenant);
    cr.setGroup(group);
    // use local config first
    //先從本地緩存中加載
    String content = LocalConfigInfoProcessor.getFailover(worker.getAgentName(), dataId, group, tenant);
    if (content != null) {
        LOGGER.warn("[{}] [get-config] get failover ok, dataId={}, group={}, tenant={}, config={}",
                worker.getAgentName(), dataId, group, tenant, ContentUtils.truncateContent(content));
        cr.setContent(content);
        String encryptedDataKey = LocalEncryptedDataKeyProcessor
                .getEncryptDataKeyFailover(agent.getName(), dataId, group, tenant);
        cr.setEncryptedDataKey(encryptedDataKey);
        configFilterChainManager.doFilter(null, cr);
        content = cr.getContent();
        return content;
    }
    try {
        //從服務(wù)器獲取配置
        ConfigResponse response = worker.getServerConfig(dataId, group, tenant, timeoutMs, false);
        cr.setContent(response.getContent());
        cr.setEncryptedDataKey(response.getEncryptedDataKey());
        configFilterChainManager.doFilter(null, cr);
        content = cr.getContent();
        return content;
    } catch (NacosException ioe) {
        if (NacosException.NO_RIGHT == ioe.getErrCode()) {
            throw ioe;
        }
        LOGGER.warn("[{}] [get-config] get from server error, dataId={}, group={}, tenant={}, msg={}",
                worker.getAgentName(), dataId, group, tenant, ioe.toString());
    }
    LOGGER.warn("[{}] [get-config] get snapshot ok, dataId={}, group={}, tenant={}, config={}",
            worker.getAgentName(), dataId, group, tenant, ContentUtils.truncateContent(content));
    content = LocalConfigInfoProcessor.getSnapshot(worker.getAgentName(), dataId, group, tenant);
    cr.setContent(content);
    String encryptedDataKey = LocalEncryptedDataKeyProcessor
            .getEncryptDataKeyFailover(agent.getName(), dataId, group, tenant);
    cr.setEncryptedDataKey(encryptedDataKey);
    configFilterChainManager.doFilter(null, cr);
    content = cr.getContent();
    return content;
}

將NacosPropertySource加入composite的第一個(gè)

//com.alibaba.cloud.nacos.client.NacosPropertySourceLocator#addFirstPropertySource
private void addFirstPropertySource(final CompositePropertySource composite,
      NacosPropertySource nacosPropertySource, boolean ignoreEmpty) {
   if (null == nacosPropertySource || null == composite) {
      return;
   }
   if (ignoreEmpty && nacosPropertySource.getSource().isEmpty()) {
      return;
   }
   composite.addFirstPropertySource(nacosPropertySource);
}

3.2、加載extention

private void loadExtConfiguration(CompositePropertySource compositePropertySource) {
    //獲取extention節(jié)點(diǎn)的配置信息
   List<NacosConfigProperties.Config> extConfigs = nacosConfigProperties
         .getExtensionConfigs();
    //如果不為空,加載
   if (!CollectionUtils.isEmpty(extConfigs)) {
      checkConfiguration(extConfigs, "extension-configs");
      loadNacosConfiguration(compositePropertySource, extConfigs);
   }
}

3.3、加載主配置文件

private void loadApplicationConfiguration(
      CompositePropertySource compositePropertySource, String dataIdPrefix,
      NacosConfigProperties properties, Environment environment) {
   //獲取文件擴(kuò)展名
   String fileExtension = properties.getFileExtension();
    //獲取group
   String nacosGroup = properties.getGroup();
   // load directly once by default
    //加載nacos的配置
   loadNacosDataIfPresent(compositePropertySource, dataIdPrefix, nacosGroup,
         fileExtension, true);
   // load with suffix, which have a higher priority than the default
    //加載帶后綴的配置,優(yōu)先級高于上一個(gè)
   loadNacosDataIfPresent(compositePropertySource,
         dataIdPrefix + DOT + fileExtension, nacosGroup, fileExtension, true);
   // Loaded with profile, which have a higher priority than the suffix
   for (String profile : environment.getActiveProfiles()) {
      String dataId = dataIdPrefix + SEP1 + profile + DOT + fileExtension;
       //加載帶profile,文件格式后綴的配置,優(yōu)先級高于上一個(gè)
      loadNacosDataIfPresent(compositePropertySource, dataId, nacosGroup,
            fileExtension, true);
   }
}

這里會(huì)加載至少三個(gè)nacos上面的配置文件,按優(yōu)先級依次為application,application.yaml,application-dev.yaml。

到此這篇關(guān)于Spring Cloud Alibaba Nacos Config加載配置詳解流程的文章就介紹到這了,更多相關(guān)Spring Cloud Alibaba Nacos Config 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • springmvc處理異步請求的示例

    springmvc處理異步請求的示例

    這篇文章主要介紹了springmvc處理異步請求的示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-01-01
  • 詳解Java中多進(jìn)程編程的實(shí)現(xiàn)

    詳解Java中多進(jìn)程編程的實(shí)現(xiàn)

    這篇文章主要介紹了詳解Java中多進(jìn)程編程的實(shí)現(xiàn),和多線程一樣,多進(jìn)程同樣是實(shí)現(xiàn)并發(fā)的一種方式,需要的朋友可以參考下
    2015-11-11
  • Java日常練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(63)

    Java日常練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(63)

    下面小編就為大家?guī)硪黄狫ava基礎(chǔ)的幾道練習(xí)題(分享)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧,希望可以幫到你
    2021-08-08
  • Java二維數(shù)組查找功能代碼實(shí)現(xiàn)

    Java二維數(shù)組查找功能代碼實(shí)現(xiàn)

    這篇文章主要介紹了Java二維數(shù)組查找功能代碼實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-06-06
  • java+MongoDB實(shí)現(xiàn)存圖片、下載圖片的方法示例

    java+MongoDB實(shí)現(xiàn)存圖片、下載圖片的方法示例

    這篇文章主要介紹了java+MongoDB實(shí)現(xiàn)存圖片、下載圖片的方法,結(jié)合實(shí)例形式詳細(xì)分析了java結(jié)合MongoDB實(shí)現(xiàn)圖片的存儲(chǔ)與下載相關(guān)操作技巧,需要的朋友可以參考下
    2019-09-09
  • java程序員常見的sql錯(cuò)誤

    java程序員常見的sql錯(cuò)誤

    當(dāng)Java程序員在SQL中要寫個(gè)查詢語句是很簡單的。但在Java里類似的語句卻不容易,因?yàn)槌绦騿T不僅要反復(fù)考慮編程范式,而且也要考慮算法的問題。下面我們來看看這幾個(gè)常見的錯(cuò)誤吧
    2019-06-06
  • Springbootadmin與security沖突問題及解決

    Springbootadmin與security沖突問題及解決

    這篇文章主要介紹了Springbootadmin與security沖突問題及解決方案,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-08-08
  • 吊打Java面試官!整理了一周的Spring面試大全(附答案)

    吊打Java面試官!整理了一周的Spring面試大全(附答案)

    這篇文章主要介紹了Spring面試資料(附答案)建議收藏留存,學(xué)Java的小伙伴都知道Spring是面試的必問環(huán)節(jié),看完了一天就可掌握數(shù)據(jù)結(jié)構(gòu)和算法的面試題,快來看看吧
    2021-08-08
  • nacos配置實(shí)例權(quán)重不生效問題

    nacos配置實(shí)例權(quán)重不生效問題

    這篇文章主要介紹了nacos配置實(shí)例權(quán)重不生效問題及解決方案,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-07-07
  • servlet之session工作原理簡介_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理

    servlet之session工作原理簡介_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理

    這篇文章主要介紹了servlet之session工作原理簡介,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-07-07

最新評論

华安县| 连山| 尖扎县| 通河县| 小金县| 深州市| 定南县| 乐都县| 顺平县| 全椒县| 策勒县| 安徽省| 会宁县| 定远县| 通榆县| 牙克石市| 大方县| 松滋市| 泰安市| 金湖县| 定兴县| 白银市| 晴隆县| 星子县| 武宣县| 陇西县| 福清市| 九江市| 贺兰县| 桐庐县| 红桥区| 京山县| 清徐县| 韶山市| 黔江区| 静安区| 邛崃市| 香河县| 宁乡县| 黄大仙区| 金堂县|