承接前文springcloud情操陶冶-springcloud context(二),本文将在前文基础上浅析下ConfigServer的工作原理
前话
根据前文得知,bootstrapContext引入了PropertySourceLocator接口供外部源加载配置,但作用是应用于子级ApplicationContext的环境变量Environment上,并不做更新维护操作。
具体的加载与维护更新外部源的配置信息,还是得有ConfigServer来完成,这也是本文分析的重点。
监听器
在这之前,笔者先查看此板块关联的监听器,因为其比前文分析的BootstrapApplicationListener监听器优先还高,不过内部代码很简单,笔者直接查看其复写的方法
@Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { ConfigurableEnvironment environment = event.getEnvironment(); if (!environment.resolvePlaceholders("${spring.cloud.config.enabled:false}") .equalsIgnoreCase("true")) { if (!environment.getPropertySources().contains(this.propertySource.getName())) { environment.getPropertySources().addLast(this.propertySource); } } }代码意思很简单,针对环境变量中spring.cloud.config.enabled属性如果值不为true则设置为false。根据官方上的代码注释来看,是用于屏蔽HTTP方式的访问,默认是开启的。也就是屏蔽了ConfigServer暴露Restful方式的接口访问,其中该属性可通过System系统变量或者SpringApplicationBuilder类来进行设置,具体读者可查阅其官方注释
这个影响小,我们直接去查看其如何去加载外部源的
BootstrapContext关联类
优先分析与bootstrapContext相关的类,通过查看其板块下的spring.factories文件对应的BootstrapConfiguration键值
# Bootstrap components org.springframework.cloud.bootstrap.BootstrapConfiguration=\ org.springframework.cloud.config.server.bootstrap.ConfigServerBootstrapConfiguration,\ org.springframework.cloud.config.server.config.EncryptionAutoConfiguration笔者挑选ConfigServerBootstrapConfiguration类作为主要的分析源头,内部的源码比较简单,笔者则全部放出来
// 系统变量或者bootstrap.properties文件指定了spring.cloud.config.server.bootstrap属性则生效 @Configuration @ConditionalOnProperty("spring.cloud.config.server.bootstrap") public class ConfigServerBootstrapConfiguration { @EnableConfigurationProperties(ConfigServerProperties.class) @Import({ EnvironmentRepositoryConfiguration.class }) protected static class LocalPropertySourceLocatorConfiguration { @Autowired private EnvironmentRepository repository; @Autowired private ConfigClientProperties client; @Autowired private ConfigServerProperties server; // 加载外部源入口 @Bean public EnvironmentRepositoryPropertySourceLocator environmentRepositoryPropertySourceLocator() { return new EnvironmentRepositoryPropertySourceLocator(this.repository, this.client.getName(), this.client.getProfile(), getDefaultLabel()); } private String getDefaultLabel() { if (StringUtils.hasText(this.client.getLabel())) { return this.client.getLabel(); } else if (StringUtils.hasText(this.server.getDefaultLabel())) { return this.server.getDefaultLabel(); } return null; } } }根据当前环境下是否存在spring.cloud.config.server.bootstrap属性来决定是否通过Git/SVN/Vault等方式(下文将提及)加载外部源至相应的ConfigurableEnvironment对象中
具体通过什么方式获取外部资源则交由EnvironmentRepository接口去实现,我们先看下此接口的方法
public
