关于Nacos config源码解析

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值