Nacos配置服务的源码解析
Nacos源码版本为 2.1.2 RELEASE
从Nacos的源代码分析Nacos Config的实现
NacosConfigAutoConfiguration
负责Nacos配置服务的自动配置
如果 spring.cloud.nacos.config.enabled(默认为true)为false时因为ConditionalOnProperty注解不导入到Spring Factory。
装配的Bean:
NacosConfigProperties:Nacos配置文件POJO,负责通过Spring的配置功能从配置文件中加载nacos的配置(前缀为spring.cloud.nacos)。创建时会考虑ApplicationContext的层次性。使用方法assembleConfigServiceProperties封装成Properties。
nacosRefreshProperties:Nacos是否刷新配置。默认为true。 (该类于2022年2月28日发布的最新版本2021.0.1.0已经删除,定义在EnableAutoConfiguration加载时判断是否开启)
NacosRefreshHistory:Nacos刷新历史,存储Nacos的刷新历史。历史记录时间戳、DataId、Group、以及数据的摘要(MD5)。最多存储最新的MAX_SIZE(20)条记录。用于在Endpoint中展示。
NacosConfigManager:Nacos配置管理器,接收一个(依赖于)NacosConfigProperties,并且创建(通过NacosFactory.createConfigService)、管理(提供getter)ConfigServer(配置服务器)、NacosConfigProperties(配置服务属性) 对象。
NacosContextRefresher:Nacos上下文刷新器,接收(依赖于)NacosConfigManager、
Nacos Config实现
NacosPropertySourceLocator
Nacos Config通过使用Spring Cloud提供的PropertySourceLocator进行资源定位。Nacos创建其实现类NacosPropertySourceLocator定位配置服务器上的配置文件。
/**
* Strategy for locating (possibly remote) property sources for the Environment.
* Implementations should not fail unless they intend to prevent the application from
* starting.
*
* @author Dave Syer
*
*/
public interface PropertySourceLocator {
/**
* @param environment The current Environment.
* @return A PropertySource, or null if there is none.
*
* @throws IllegalStateException if there is a fail-fast condition.
*/
PropertySource<?> locate(Environment environment);
}
首先看一下PropertySourceLocator是干什么的。PropertySourceLocator让spring读取我们自定义的配置文件(注册到Spring Environment),然后使用 @Value注解即可读取到配置文件中的属性,这解释了为什么Nacos等配置中心可以直接使用Value注解进行配置的读取。值得一提,这是基于SPI(Service Provider Interface)机制的,需要在META-INF/spring.factories中定义org.springframework.cloud.boot