百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程网 > 正文

Spring Cloud Config 规范 springcloud config 简书

yuyutoo 2024-10-12 00:16 3 浏览 0 评论

Spring Cloud Config 规范

首先Spring Cloud 是基于 Spring 来扩展的,Spring 本身就提供当创建一个Bean时可从Environment 中将一些属性值通过@Value的形式注入到业务代码中的能力。那Spring Cloud Config 要解决的问题就是:

  1. 如何将配置加载到 Environment 。
  2. 配置变更时,如何控制 Bean 是否需要 create,重新触发一次 Bean 的初始化,才能将 @Value 注解指定的字段从 Environment 中重新注入。
  3. 配置变更时,如何控制新的配置会更新到 Environment 中,才能保证配置变更时可注入最新的值。

要解决以上三个问题:Spring Cloud Config 规范中刚好定义了核心的三个接口:

  1. PropertySourceLocator:抽象出这个接口,就是让用户可定制化的将一些配置加载到 Environment。这部分的配置获取遵循了 Spring Cloud Config 的理念,即希望能从外部储存介质中来 loacte。
  2. RefreshScope: Spring Cloud 定义这个注解,是扩展了 Spring 原有的 Scope 类型。用来标识当前这个 Bean 是一个refresh 类型的 Scope。其主要作用就是可以控制 Bean 的整个生命周期。
  3. ContextRefresher:抽象出这个 Class,是让用户自己按需来刷新上下文(比如当有配置刷新时,希望可以刷新上下文,将最新的配置更新到 Environment,重新创建 Bean 时,就可以从 Environment 中注入最新的配置)。

Spring Cloud Config 原理

Spring Cloud Config 的启动过程

1、如何将配置加载到Environment:PropertySourceLocator

在整个 Spring Boot 启动的生命周期过程中,有一个阶段是 prepare environment。在这个阶段,会publish 一个 ApplicationEnvironmentPreparedEvent,通知所有对这个事件感兴趣的 Listener,提供对 Environment 做更多的定制化的操作。Spring Cloud 定义了一个BootstrapApplicationListener,在 BootstrapApplicationListener 的处理过程中有一步非常关键的操作如下所示:

private ConfigurableApplicationContext bootstrapServiceContext(
 ConfigurableEnvironment environment, final SpringApplication application,
 String configName) {
 //省略
 ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
 // Use names and ensure unique to protect against duplicates
 List<String> names = new ArrayList<>(SpringFactoriesLoader
 .loadFactoryNames(BootstrapConfiguration.class, classLoader));
 //省略
 }

这是 Spring 的工厂加载机制,可通过在 META-INF/spring.factories 文件中配置一些程序中预定义的一些扩展点。比如 Spring Cloud 这里的实现,可以看到 BootstrapConfiguration 不是一个具体的接口,而是一个注解。通过这种方式配置的扩展点好处是不局限于某一种接口的实现,而是同一类别的实现。可以查看 spring-cloud-context 包中的 spring.factories 文件关于BootstrapConfiguration的配置,有一个比较核心入口的配置就是:

org.springframework.cloud.bootstrap.BootstrapConfiguration=\
org.springframework.cloud.bootstrap.config.PropertySourceBootstrapConfiguration

可以发现 PropertySourceBootstrapConfiguration 实现了 ApplicationContextInitializer 接口,其目的就是在应用程序上下文初始化的时候做一些额外的操作。在 Bootstrap 阶段,会通过 Spring Ioc 的整个生命周期来初始化所有通过key为_org.springframework.cloud.bootstrap.BootstrapConfiguration_ 在 spring.factories 中配置的 Bean。Spring Cloud Alibaba Nacos Config 的实现就是通过该key来自定义一些在Bootstrap 阶段需要初始化的一些Bean。在该模块的 spring.factories 配置文件中可以看到如下配置:

org.springframework.cloud.bootstrap.BootstrapConfiguration=\
org.springframework.cloud.alibaba.nacos.NacosConfigBootstrapConfiguration

在 Bootstrap 阶段初始化的过程中,会获取所有 ApplicationContextInitializer 类型的 Bean,并设置回SpringApplication主流程当中。如下 BootstrapApplicationListener 类中的部分代码所示:

private void apply(ConfigurableApplicationContext context,
 SpringApplication application, ConfigurableEnvironment environment) {
 @SuppressWarnings("rawtypes")
 //这里的 context 是一个 bootstrap 级别的 ApplicationContext,这里已经含有了在 bootstrap阶段所有需要初始化的 Bean。
 //因此可以获取 ApplicationContextInitializer.class 类型的所有实例
 List<ApplicationContextInitializer> initializers = getOrderedBeansOfType(context,
 ApplicationContextInitializer.class);
 //设置回 SpringApplication 主流程当中
 application.addInitializers(initializers 
 .toArray(new ApplicationContextInitializer[initializers.size()]));
 
 //省略...
}

这样一来,就可以通过在 SpringApplication 的主流程中来回调这些ApplicationContextInitializer 的实例,做一些初始化的操作。如下 SpringApplication 类中的部分代码所示:

private void prepareContext(ConfigurableApplicationContext context,
 ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
 ApplicationArguments applicationArguments, Banner printedBanner) {
 context.setEnvironment(environment);
 postProcessApplicationContext(context);
 //回调在BootstrapApplicationListener中设置的ApplicationContextInitializer实例
 applyInitializers(context);
 listeners.contextPrepared(context);
 //省略...
}
protected void applyInitializers(ConfigurableApplicationContext context) {
 for (ApplicationContextInitializer initializer : getInitializers()) {
 Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(
 initializer.getClass(), ApplicationContextInitializer.class);
 Assert.isInstanceOf(requiredType, context, "Unable to call initializer.");
 initializer.initialize(context);
 }
}

在 applyInitializers 方法中,会触发 PropertySourceBootstrapConfiguration 中的 initialize 方法。如下所示:

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
 CompositePropertySource composite = new CompositePropertySource(
 BOOTSTRAP_PROPERTY_SOURCE_NAME);
 AnnotationAwareOrderComparator.sort(this.propertySourceLocators);
 boolean empty = true;
 ConfigurableEnvironment environment = applicationContext.getEnvironment();
 for (PropertySourceLocator locator : this.propertySourceLocators) {
 PropertySource<?> source = null;
 //回调所有实现PropertySourceLocator接口实例的locate方法,
 source = locator.locate(environment);
 if (source == null) {
 continue;
 }
 
 composite.addPropertySource(source);
 empty = false;
 }
 if (!empty) {
 //从当前Enviroment中获取 propertySources
 MutablePropertySources propertySources = environment.getPropertySources();
 //省略...
 //将composite中的PropertySource添加到当前应用上下文的propertySources中
 insertPropertySources(propertySources, composite);
 //省略...
 }

在这个方法中会回调所有实现 PropertySourceLocator 接口实例的locate方法,

locate 方法返回一个 PropertySource 的实例,统一add到CompositePropertySource实例中。如果 composite 中有新加的PropertySource,最后将composite中的PropertySource添加到当前应用上下文的propertySources中。Spring Cloud Alibaba Nacos Config 在 Bootstrap 阶段通过Java配置的方式初始化了一个 NacosPropertySourceLocator 类型的Bean。从而在 locate 方法中将存放在Nacos中的配置信息读取出来,将读取结果存放到 PropertySource 的实例中返回。具体如何从Nacos中读取配置信息可参考 NacosPropertySourceLocator 类的实现。

Spring Cloud Config 正是提供了PropertySourceLocator接口,来提供应用外部化配置可动态加载的能力。Spring Ioc 容器在初始化 Bean 的时候,如果发现 Bean 的字段上含有 @Value 的注解,就会从 Enviroment 中的PropertySources 来获取其值,完成属性的注入。

Spring Cloud Config 外部化配置可动态刷新

感知到外部化配置的变更这部分代码的操作是需要用户来完成的。Spring Cloud Config 只提供了具备外部化配置可动态刷新的能力,并不具备自动感知外部化配置发生变更的能力。比如如果你的配置是基于Mysql来实现的,那么在代码里面肯定要有能力感知到配置发生变化了,然后再显示的调用 ContextRefresher 的 refresh方法,从而完成外部化配置的动态刷新(只会刷新使用RefreshScope注解的Bean)。

例如在 Spring Cloud Alibaba Nacos Config 的实现过程中,Nacos 提供了对dataid 变更的Listener 回调。在对每个dataid 注册好了相应的Listener之后,如果Nacos内部通过长轮询的方式感知到数据的变更,就会回调相应的Listener,在 Listener 的实现过程中,就是通过调用 ContextRefresher 的 refresh方法完成配置的动态刷新。具体可参考 NacosContextRefresher 类的实现。

Sring Cloud Config的动态配置刷新原理图如下所示:

ContextRefresher的refresh的方法主要做了两件事:

  1. 触发PropertySourceLocator的locator方法,需要加载最新的值,并替换 Environment 中旧值
  2. Bean中的引用配置值需要重新注入一遍。重新注入的流程是在Bean初始化时做的操作,那也就是需要将refresh scope中的Bean 缓存失效,当再次从refresh scope中获取这个Bean时,发现取不到,就会重新触发一次Bean的初始化过程。

这两个操作所对应的代码如下所示:

public synchronized Set refresh() {
 Map<String, Object> before = extract(
 this.context.getEnvironment().getPropertySources());
 //1、加载最新的值,并替换Envrioment中旧值
 addConfigFilesToEnvironment();
 Set<String> keys = changes(before,
 extract(this.context.getEnvironment().getPropertySources())).keySet();
 this.context.publishEvent(new EnvironmentChangeEvent(context, keys));
 //2、将refresh scope中的Bean 缓存失效: 清空
 this.scope.refreshAll();
 return keys;
}

addConfigFilesToEnvironment 方法中发生替换的代码如下所示:

ConfigurableApplicationContext addConfigFilesToEnvironment() {
 ConfigurableApplicationContext capture = null;
 try {
 //省略...
 //1、这里会重新触发PropertySourceLoactor的locate的方法,获取最新的外部化配置
 capture = (SpringApplicationBuilder)builder.run();
 
 MutablePropertySources target = this.context.getEnvironment()
 .getPropertySources();
 String targetName = null;
 for (PropertySource<?> source : environment.getPropertySources()) {
 String name = source.getName();
 //省略..
 
 //只有不是标准的 Source 才可替换
 if (!this.standardSources.contains(name)) {
 if (target.contains(name)) {
 //开始用新的PropertySource替换旧值
 target.replace(name, source);
 }
 //
 }
 }
 }
 //
 return capture;
}

this.scope.refreshAll() 清空缓存的操作代码如下所示:

@Override
 public void destroy() {
 List<Throwable> errors = new ArrayList<Throwable>();
 //清空Refresh Scope 中的缓存
 Collection<BeanLifecycleWrapper> wrappers = this.cache.clear();
 //省略...
 }

为了验证每次配置刷新时,Bean 是新创建的,特意写了一个Demo 验证了下,如下所示:

Acm Properties: beijing-region
//刷新前
Object Instance is :com.alibaba.demo.normal.ConfigProperties@1be9634
2018-11-01 19:16:32.535 INFO 27254 --- [gPullingdefault] startup date [Thu Nov 01 19:16:32 CST 2018]; root of context hierarchy
Acm Properties: qingdao-region
//刷新后
Object Instance is :com.alibaba.demo.normal.ConfigProperties@2c6965e0

Spring Cloud Config 扩展Scope的核心类:RefreshScope

可以看到上面的代码中有 this.scope.refreshAll(),其中的scope就是RefreshScope。是用来存放scope类型为refresh类型的Bean(即使用RefreshScope注解标识的Bean),也就是说当一个Bean既不是singleton也不是prototype时,就会从自定义的Scope中去获取(Spring 允许自定义Scope),然后调用Scope的get方法来获取一个实例,Spring Cloud 正是扩展了Scope,从而控制了整个 Bean 的生命周期。当配置需要动态刷新的时候, 调用this.scope.refreshAll()这个方法,就会将整个RefreshScope的缓存清空,完成配置可动态刷新的可能。

更多关于Scope的分析请参考 这里

https://www.cnblogs.com/noahsark/p/spring-scope-analysis.html

后续

关于ContextRefresh 和 RefreshScope的初始化配置是在RefreshAutoConfiguration类中完成的。而RefreshAutoConfiguration类初始化的入口是在spring-cloud-context中的META-INF/spring.factories中配置的。从而完成整个和动态刷新相关的Bean的初始化操作。

作者:中间件小哥

相关推荐

自卑的人容易患抑郁症吗?(自卑会导致抑郁吗)

Filephoto[Photo/IC]Lowself-esteemmakesusfeelbadaboutourselves.Butdidyouknowthatovert...

中考典型同(近)义词组(同义词考题)

中考典型同(近)义词组...

WPF 消息传递简明教程(wpf messagebox.show)

...

BroadcastReceiver的原理和使用(broadcast-suppression)

一、使用中注意的几点1.动态注册、静态注册的优先级在AndroidManifest.xml中静态注册的receiver比在代码中用registerReceiver动态注册的优先级要低。发送方在send...

Arduino通过串口透传ESP 13板与java程序交互

ESP13---是一个无线板子,配置通过热点通信Arduino通过串口透传ESP13板与java程序交互...

zookeeper的Leader选举源码解析(zookeeper角色选举角色包括)

作者:京东物流梁吉超zookeeper是一个分布式服务框架,主要解决分布式应用中常见的多种数据问题,例如集群管理,状态同步等。为解决这些问题zookeeper需要Leader选举进行保障数据的强一致...

接待外国人英文口语(接待外国友人的英语口语对话)

接待外国人英文口语询问访客身份:  MayIhaveyourname,please?  请问您贵姓?  Whatcompanyareyoufrom?  您是哪个公司的?  Could...

一文深入理解AP架构Nacos注册原理

Nacos简介Nacos是一款阿里巴巴开源用于管理分布式微服务的中间件,能够帮助开发人员快速实现动态服务发现、服务配置、服务元数据及流量管理等。这篇文章主要剖析一下Nacos作为注册中心时其服务注册与...

Android面试宝典之终极大招(android面试及答案)

以下内容来自兆隆IT云学院就业部,根据多年成功就业服务经验,以及职业素养课程部分内容,归纳总结:18.请描述一下Intent和IntentFilter。Android中通过Intent...

除了Crontab,Swoole Timer也可以实现定时任务的

一般的定时器是怎么实现的呢?我总结如下:1.使用Crontab工具,写一个shell脚本,在脚本中调用PHP文件,然后定期执行该脚本;2.ignore_user_abort()和set_time_li...

Spark源码阅读:DataFrame.collect 作业提交流程思维导图

本文分为两个部分:作业提交流程思维导图关键函数列表作业提交流程思维导图...

使用Xamarin和Visual Studio开发Android可穿戴设备应用

搭建开发环境我们需要做的第一件事情是安装必要的工具。因此,你需要首先安装VisualStudio。如果您使用的是VisualStudio2010,2012或2013,那么请确保它是一个专业版本或...

Android开发者必知的5个开源库(android 开发相关源码精编解析)

过去的时间里,Android开发逐步走向成熟,一个个与Android相关的开发工具也层出不穷。不过,在面对各种新鲜事物时,不要忘了那些我们每天使用的大量开源库。在这里,向大家介绍的就是,在这个任劳任怨...

Android事件总线还能怎么玩?(android实现事件处理的步骤)

顾名思义,AndroidEventBus是一个Android平台的事件总线框架,它简化了Activity、Fragment、Service等组件之间的交互,很大程度上降低了它们之间的耦合,使我们的代码...

Android 开发中文引导-应用小部件

应用小部件是可以嵌入其它应用(例如主屏幕)并收到定期更新的微型应用视图。这些视图在用户界面中被叫做小部件,并可以用应用小部件提供者发布。可以容纳其他应用部件的应用组件叫做应用部件的宿主(1)。下面的截...

取消回复欢迎 发表评论: