Nacos 配置中心之环境准备
Nacos 配置中心的工作流程是怎么样的呢?首先启动 SpringBoot 项目,在启动项目之后,需要把远程服务器的配置文件加载到 Spring 容器中
@SpringBootApplication
public class SpringCloudNacosConfigApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context=
SpringApplication.run(SpringCloudNacosConfigApplication.class, args);
String info=context.getEnvironment().getProperty("info");
System.out.println(info);
}
}
复制代码
重点在于 Environment 的获取,那么如何从远处服务器上的配置加载到 Environment?
我们看一下 SpringBoot 启动的时候,SpringApplication.run()方法做了哪些环境准备
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
configureHeadlessProperty();
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
//环境准备
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
configureIgnoreBeanInfo(environment);
Banner printedBanner = printBanner(environment);
context = createApplicationContext();
exceptionReporters = getSpringFactoriesInstances(
SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
refreshContext(context);
afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
listeners.started(context);
callRunners(context, applicationArguments);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, listeners);
throw new IllegalStateException(ex);
}
try {
listeners.running(context);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, null);
throw new IllegalStateException(ex);
}
return context;
}
复制代码
获取监听并启动监听
根据传入的参数创建 applicationArguments 对象
调用 prepareEnvironment 方法,进行环境准备
打印 banner,准备上下文,刷新上下文,然后执行刷新之后操作等等
租后返回 context 上下文
我们看看 prepareEnvironment 方法做了什么
prepareEnvironment()方法
private ConfigurableEnvironment prepareEnvironment(
SpringApplicationRunListeners listeners,
ApplicationArguments applicationArguments) {
// Create and configure the environment
ConfigurableEnvironment environment = getOrCreateEnvironment();
configureEnvironment(environment, applicationArguments.getSourceArgs());
listeners.environmentPrepared(environment);
bindToSpringApplication(environment);
if (!this.isCustomEnvironment) {
environment = new EnvironmentConverter(getClassLoader())
.convertEnvironmentIfNecessary(environment, deduceEnvironmentClass());
}
ConfigurationPropertySources.attach(environment);
return environment;
}
复制代码
获取或则创建环境,在 listeners.environmentPrepared(environment);中发布一个 ApplicationEnvironmentPreparedEvent 事件,所有定义这个的 Listener 监听器都会监听到这个事件。
BootstrapApplicationListener 就会收到该事件并进行处理
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
ConfigurableEnvironment environment = event.getEnvironment();
if (!environment.getProperty("spring.cloud.bootstrap.enabled", Boolean.class,
true)) {
return;
}
// don't listen to events in a bootstrap context
if (environment.getPropertySources().contains(BOOTSTRAP_PROPERTY_SOURCE_NAME)) {
return;
}
ConfigurableApplicationContext context = null;
String configName = environment
.resolvePlaceholders("${spring.cloud.bootstrap.name:bootstrap}");
for (ApplicationContextInitializer<?> initializer : event.getSpringApplication()
.getInitializers()) {
if (initializer instanceof ParentContextApplicationContextInitializer) {
context = findBootstrapContext(
(ParentContextApplicationContextInitializer) initializer,
configName);
}
}
if (context == null) {
context = bootstrapServiceContext(environment, event.getSpringApplication(),
configName);
event.getSpringApplication()
.addListeners(new CloseContextOnFailureApplicationListener(context));
}
apply(context, event.getSpringApplication(), environment);
}
复制代码
在 bootstrapServiceContext 方法中调用 builder.sources(BootstrapImportSelectorConfiguration.class),进行自动装配,这里就不贴具体的代码了,我们看一下 BootstrapImportSelectorConfiguration 这个类做了什么
BootstrapImportSelectorConfiguration 类
BootstrapImportSelectorConfiguration 是配置类
@Configuration
@Import(BootstrapImportSelector.class)
public class BootstrapImportSelectorConfiguration {
}
复制代码
用 @Import 导入 BootstrapImportSelector 实现自动装配
BootstrapImportSelector 的 selectImports 方法:
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
// Use names and ensure unique to protect against duplicates
List<String> names = new ArrayList<>(SpringFactoriesLoader
.loadFactoryNames(BootstrapConfiguration.class, classLoader));
names.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(
this.environment.getProperty("spring.cloud.bootstrap.sources", ""))));
List<OrderedAnnotatedElement> elements = new ArrayList<>();
for (String name : names) {
try {
elements.add(
new OrderedAnnotatedElement(this.metadataReaderFactory, name));
}
catch (IOException e) {
continue;
}
}
AnnotationAwareOrderComparator.sort(elements);
String[] classNames = elements.stream().map(e -> e.name).toArray(String[]::new);
return classNames;
}
复制代码
利用 Spring 的 SPI 机制查找 META-INF/spring.factories 扩展点
key 是 BootstrapConfiguration
在 spring-cloud-context.jar 中的 spring.factories:PropertySourceBootstrapConfiguration
# Bootstrap components
org.springframework.cloud.bootstrap.BootstrapConfiguration=\
org.springframework.cloud.bootstrap.config.PropertySourceBootstrapConfiguration,\
org.springframework.cloud.bootstrap.encrypt.EncryptionBootstrapConfiguration,\
org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration,\
org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration
复制代码
在 spring-cloud-context.jar 中的 spring.factories:
NacosConfigBootstrapConfiguration
org.springframework.cloud.bootstrap.BootstrapConfiguration=\
com.alibaba.cloud.nacos.NacosConfigBootstrapConfiguration
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.alibaba.cloud.nacos.NacosConfigAutoConfiguration,\
com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration
org.springframework.boot.diagnostics.FailureAnalyzer=\
com.alibaba.cloud.nacos.diagnostics.analyzer.NacosConnectionFailureAnalyzer
复制代码
水落石出了,这里自动装配了 NacosConfigBootstrapConfiguration 配置类
总结
这就是 Nacos 配置中心的环境准备方面,从 SpringBoot 项目启动类的环境准备的方法入手,通过 BootstrapApplicationListener 类的监听方法,调用了 builder.sources(BootstrapImportSelectorConfiguration.class)加载了 BootstrapImportSelectorConfiguration 类,它的 selectImports()方法中利用 Spring 的 SPI 扩展机制记载了 key 为 BootstrapConfiguration 定义的一些 nacos 中类,从而对 nacos 的启动环境做了准备。
其实 nacos 最重要的功能就是注册中心和配置中心,作为 nacos 的使用者,我们要掌握好 nacos 的流程和工作原理,才能定位到问题,并在合适的业务场景中进行对 nacos 服务的功能优化和利用好 nacos,这篇文章仅仅是对 nacos 作为配置中心功能的环境准备方面的结束,后续还会进一步分析 nacos 配置文件的流程和工作原理。如果你觉得这篇文章对你有帮助的话,欢迎给我留言点赞评论转发!
评论