前言
Nacos Spring Cloud的使用方法与Nacos Spring Boot的使用方法类似,都是通过添加依赖与在配置文件中增加配置来完成接入。需要注意的是在Spring Cloud应用中必须要配置spring.application.name,因为它是构成 Nacos 配置管理dataId字段的一部分,在Nacos Spring Cloud中配置文件的dataId完整格式为prefix-spring.profiles.active.file-extension,当然Nacos Spring Cloud也支持通过配置扩展属性字段来完成其他的配置项加载。在使用上Nacos Spring Cloud相对来说更为简单,主要利用的是Spring Cloud原生注解@RefreshScope来完成配置的自动刷新,如下代码片段所示。
@RestController
@RequestMapping("/config")
@RefreshScope
public class ConfigController {
@Value("${useLocalCache:false}")
private boolean useLocalCache;
@RequestMapping("/get")
public boolean get() {
return useLocalCache;
}
}
依旧是从META-INF/spring.factories文件入手,Nacos Spring Cloud自动配置主要包含了以下几个关键的类:
- NacosConfigBootstrapConfiguration: 负责Bootstrap上下文创建时的自动配置
- NacosConfigAutoConfiguration:负责应用上下文创建时的自动配置
- NacosConfigEndpointAutoConfiguration:负责配置Actuator相关端点
- NacosConnectionFailureAnalyzer:配置错误分析器
- NacosJsonPropertySourceLoader:配置Json格式属性解析器
- NacosXmlPropertySourceLoader:配置Xml格式属性解析器
- NacosLoggingListener:负责日志模块的配置重新加载
本文将从以上的类中挑选几个关键的类进行源码的分析,简要的阐述Nacos Spring Cloud的工作原理。
NacosConfigBootstrapConfiguration
A Spring Cloud application operates by creating a “bootstrap” context, which is a parent context for the main application. It is responsible for loading configuration properties from the external sources and for decrypting properties in the local external configuration files. The two contexts share an
Environment
, which is the source of external properties for any Spring application. By default, bootstrap properties (notbootstrap.properties
but properties that are loaded during the bootstrap phase) are added with high precedence, so they cannot be overridden by local configuration.
在Spring Cloud应用中,应用的ApplicationContext创建于Bootstrap的ApplicationContext之上。如文档上所述,Bootstrap Context负责从外部配置源加载配置文件,默认情况下拥有最高优先级的配置。属性文件默认来源于boostrap.yml配置文件,还可以通过在Bootstrap Context中配置PropertySourceLocators来自定义配置文件的加载。NacosConfigBootstrapConfiguration则是负责在Bootstrap的ApplicationContext上定义需要的工具类Bean来完成远程配置属性的加载。在NacosConfigBootstrapConfiguration中配置了三种Bean,分别是用于属性定义的NacosConfigProperties,用于创建ConfigService的NacosConfigManager,以及用于注入配置文件的NacosPropertySourceLocator。
其他两个Bean相对比较简单,我们重点看一下NacosPropertySourceLocator是如何实现的。NacosPropertySourceLocator实现了PropertySourceLocator接口,如上面所述实现了PropertySourceLocator的Bean会被用于在Bootstrap创建时加载自定义的属性。在locate方法中,首先会利用NacosConfigManager创建一个ConfigService,随后是对默认应用dataId的解析,最后创建一个组合“Nacos”属性,分别对配置文件中的Shared配置、Ext配置以及应用本身的配置进行加载。
@Override
public PropertySource<?> locate(Environment env) {
nacosConfigProperties.setEnvironment(env);
ConfigService configService = nacosConfigManager.getConfigService();
if (null