Spring Cloud针对Environment的属性源功能做了增强,

在spring-cloud-contenxt这个包中,提供了PropertySourceLocator接口,用来实现属性文件加载的扩展。我们可以通过这个接口来扩展自己的外部化配置加载。这个接口的定义如下

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);
}

locate这个抽象方法,需要返回一个PropertySource对象。

这个PropertySource就是Environment中存储的属性源。 也就是说,我们如果要实现自定义外部化配置加载,只需要实现这个接口并返回PropertySource即可。

按照这个思路,我们按照下面几个步骤来实现外部化配置的自定义加载。

自定义PropertySource

既然PropertySourceLocator需要返回一个PropertySource,那我们必须要定义一个自己的PropertySource,来从外部获取配置来源。

GpDefineMapPropertySource 表示一个以Map结果作为属性来源的类。

/**
* 咕泡教育,ToBeBetterMan
* Mic老师微信: mic4096
* 微信公众号: 跟着Mic学架构
* https://ke.gupaoedu.cn
* 使用Map作为属性来源。
**/
public class GpDefineMapPropertySource extends MapPropertySource {
/**
* Create a new {@code MapPropertySource} with the given name and {@code Map}.
*
* @param name the associated name
* @param source the Map source (without {@code null} values in order to get
* consistent {@link #getProperty} and {@link #containsProperty} behavior)
*/
public GpDefineMapPropertySource(String name, Map<String, Object> source) {
super(name, source);
} @Override
public Object getProperty(String name) {
return super.getProperty(name);
} @Override
public String[] getPropertyNames() {
return super.getPropertyNames();
}
}

扩展PropertySourceLocator

扩展PropertySourceLocator,重写locate提供属性源。

而属性源是从gupao.json文件加载保存到自定义属性源GpDefineMapPropertySource中。

public class GpJsonPropertySourceLocator implements PropertySourceLocator {

    //json数据来源
private final static String DEFAULT_LOCATION="classpath:gupao.json";
//资源加载器
private final ResourceLoader resourceLoader=new DefaultResourceLoader(getClass().getClassLoader()); @Override
public PropertySource<?> locate(Environment environment) {
//设置属性来源
GpDefineMapPropertySource jsonPropertySource=new GpDefineMapPropertySource
("gpJsonConfig",mapPropertySource());
return jsonPropertySource;
} private Map<String,Object> mapPropertySource(){
Resource resource=this.resourceLoader.getResource(DEFAULT_LOCATION);
if(resource==null){
return null;
}
Map<String,Object> result=new HashMap<>();
JsonParser parser= JsonParserFactory.getJsonParser();
Map<String,Object> fileMap=parser.parseMap(readFile(resource));
processNestMap("",result,fileMap);
return result;
}
//加载文件并解析
private String readFile(Resource resource){
FileInputStream fileInputStream=null;
try {
fileInputStream=new FileInputStream(resource.getFile());
byte[] readByte=new byte[(int)resource.getFile().length()];
fileInputStream.read(readByte);
return new String(readByte,"UTF-8");
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fileInputStream!=null){
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
//解析完整的url保存到result集合。 为了实现@Value注入
private void processNestMap(String prefix,Map<String,Object> result,Map<String,Object> fileMap){
if(prefix.length()>0){
prefix+=".";
}
for (Map.Entry<String, Object> entrySet : fileMap.entrySet()) {
if (entrySet.getValue() instanceof Map) {
processNestMap(prefix + entrySet.getKey(), result, (Map<String, Object>) entrySet.getValue());
} else {
result.put(prefix + entrySet.getKey(), entrySet.getValue());
}
}
}
}

Spring.factories

在/META-INF/spring.factories文件中,添加下面的spi扩展,让Spring Cloud启动时扫描到这个扩展从而实现GpJsonPropertySourceLocator的加载。

org.springframework.cloud.bootstrap.BootstrapConfiguration=\
com.gupaoedu.env.GpJsonPropertySourceLocator

编写controller测试

@RestController
public class ConfigController {
@Value("${custom.property.message}")
private String name; @GetMapping("/")
public String get(){
String msg=String.format("配置值:%s",name);
return msg;
}
}

阶段性总结

通过上述案例可以发现,基于Spring Boot提供的PropertySourceLocator扩展机制,可以轻松实现自定义配置源的扩展。

于是,引出了两个问题。

  1. PropertySourceLocator是在哪个被触发的?
  2. 既然能够从gupao.json中加载数据源,是否能从远程服务器上加载呢?

PropertySourceLocator加载原理

先来探索第一个问题,PropertySourceLocator的执行流程。

SpringApplication.run

在spring boot项目启动时,有一个prepareContext的方法,它会回调所有实现了ApplicationContextInitializer的实例,来做一些初始化工作。

ApplicationContextInitializer是Spring框架原有的东西, 它的主要作用就是在,ConfigurableApplicationContext类型(或者子类型)的ApplicationContext做refresh之前,允许我们对ConfiurableApplicationContext的实例做进一步的设置和处理。

它可以用在需要对应用程序上下文进行编程初始化的web应用程序中,比如根据上下文环境来注册propertySource,或者配置文件。而Config 的这个配置中心的需求恰好需要这样一个机制来完成。

public ConfigurableApplicationContext run(String... args) {
//省略代码...
prepareContext(context, environment, listeners, applicationArguments, printedBanner);
//省略代码
return context;
}

PropertySourceBootstrapConfiguration.initialize

其中,PropertySourceBootstrapConfiguration就实现了ApplicationContextInitializer,initialize方法代码如下。

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
List<PropertySource<?>> composite = new ArrayList<>();
//对propertySourceLocators数组进行排序,根据默认的AnnotationAwareOrderComparator
AnnotationAwareOrderComparator.sort(this.propertySourceLocators);
boolean empty = true;
//获取运行的环境上下文
ConfigurableEnvironment environment = applicationContext.getEnvironment();
for (PropertySourceLocator locator : this.propertySourceLocators) {
//回调所有实现PropertySourceLocator接口实例的locate方法,并收集到source这个集合中。
Collection<PropertySource<?>> source = locator.locateCollection(environment);
if (source == null || source.size() == 0) { //如果source为空,直接进入下一次循环
continue;
}
//遍历source,把PropertySource包装成BootstrapPropertySource加入到sourceList中。
List<PropertySource<?>> sourceList = new ArrayList<>();
for (PropertySource<?> p : source) {
sourceList.add(new BootstrapPropertySource<>(p));
}
logger.info("Located property source: " + sourceList);
composite.addAll(sourceList);//将source添加到数组
empty = false; //表示propertysource不为空
}
//只有propertysource不为空的情况,才会设置到environment中
if (!empty) {
//获取当前Environment中的所有PropertySources.
MutablePropertySources propertySources = environment.getPropertySources();
String logConfig = environment.resolvePlaceholders("${logging.config:}");
LogFile logFile = LogFile.get(environment);
// 遍历移除bootstrapProperty的相关属性
for (PropertySource<?> p : environment.getPropertySources()) { if (p.getName().startsWith(BOOTSTRAP_PROPERTY_SOURCE_NAME)) {
propertySources.remove(p.getName());
}
}
//把前面获取到的PropertySource,插入到Environment中的PropertySources中。
insertPropertySources(propertySources, composite);
reinitializeLoggingSystem(environment, logConfig, logFile);
setLogLevels(applicationContext, environment);
handleIncludedProfiles(environment);
}
}

上述代码逻辑说明如下。

  1. 首先this.propertySourceLocators,表示所有实现了PropertySourceLocators接口的实现类,其中就包括我们前面自定义的GpJsonPropertySourceLocator。
  2. 根据默认的 AnnotationAwareOrderComparator 排序规则对propertySourceLocators数组进行排序。
  3. 获取运行的环境上下文ConfigurableEnvironment
  4. 遍历propertySourceLocators时
  • 调用 locate 方法,传入获取的上下文environment
  • 将source添加到PropertySource的链表中
  • 设置source是否为空的标识标量empty
  1. source不为空的情况,才会设置到environment中
  • 返回Environment的可变形式,可进行的操作如addFirst、addLast
  • 移除propertySources中的bootstrapProperties
  • 根据config server覆写的规则,设置propertySources
  • 处理多个active profiles的配置信息

注意:this.propertySourceLocators这个集合中的PropertySourceLocator,是通过自动装配机制完成注入的,具体的实现在BootstrapImportSelector这个类中。

ApplicationContextInitializer的理解和使用

ApplicationContextInitializer是Spring框架原有的东西, 它的主要作用就是在,ConfigurableApplicationContext类型(或者子类型)的ApplicationContext做refresh之前,允许我们对ConfiurableApplicationContext的实例做进一步的设置和处理。

它可以用在需要对应用程序上下文进行编程初始化的web应用程序中,比如根据上下文环境来注册propertySource,或者配置文件。而Config 的这个配置中心的需求恰好需要这样一个机制来完成。

创建一个TestApplicationContextInitializer

public class TestApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext>{
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
ConfigurableEnvironment ce=applicationContext.getEnvironment();
for(PropertySource<?> propertySource:ce.getPropertySources()){
System.out.println(propertySource);
}
System.out.println("--------end");
}
}

添加spi加载

创建一个文件/resources/META-INF/spring.factories。添加如下内容

org.springframework.context.ApplicationContextInitializer= \
com.gupaoedu.example.springcloudconfigserver9091.TestApplicationContextInitializer

在控制台就可以看到当前的PropertySource的输出结果。

ConfigurationPropertySourcesPropertySource {name='configurationProperties'}
StubPropertySource {name='servletConfigInitParams'}
StubPropertySource {name='servletContextInitParams'}
PropertiesPropertySource {name='systemProperties'}
OriginAwareSystemEnvironmentPropertySource {name='systemEnvironment'}
RandomValuePropertySource {name='random'}
MapPropertySource {name='configServerClient'}
MapPropertySource {name='springCloudClientHostInfo'}
OriginTrackedMapPropertySource {name='applicationConfig: [classpath:/application.yml]'}
MapPropertySource {name='kafkaBinderDefaultProperties'}
MapPropertySource {name='defaultProperties'}
MapPropertySource {name='springCloudDefaultProperties'}

版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Mic带你学架构!

如果本篇文章对您有帮助,还请帮忙点个关注和赞,您的坚持是我不断创作的动力。欢迎关注「跟着Mic学架构」公众号公众号获取更多技术干货!

Spring Cloud 中自定义外部化扩展机制原理及实战的更多相关文章

  1. Spring Cloud中五大神兽总结(Eureka/Ribbon/Feign/Hystrix/zuul)

    Spring Cloud中五大神兽总结(Eureka/Ribbon/Feign/Hystrix/zuul) 1.Eureka Eureka是Netflix的一个子模块,也是核心模块之一.Eureka是 ...

  2. Spring Cloud Feign 自定义配置(重试、拦截与错误码处理) 实践

    Spring Cloud Feign 自定义配置(重试.拦截与错误码处理) 实践 目录 Spring Cloud Feign 自定义配置(重试.拦截与错误码处理) 实践 引子 FeignClient的 ...

  3. Spring Cloud中负载均衡器概览

    在上篇文章中(RestTemplate的逆袭之路,从发送请求到负载均衡)我们完整的分析了RestTemplate的工作过程,在分析的过程中,我们遇到过一个ILoadBalancer接口,这个接口中有一 ...

  4. Spring Cloud中Hystrix、Ribbon及Feign的熔断关系是什么?

    导读 今天和大家聊一聊在Spring Cloud微服务框架实践中,比较核心但是又很容易把人搞得稀里糊涂的一个问题,那就是在Spring Cloud中Hystrix.Ribbon以及Feign它们三者之 ...

  5. spring cloud gateway自定义过滤器

    在API网关spring cloud gateway和负载均衡框架ribbon实战文章中,主要实现网关与负载均衡等基本功能,详见代码.本节内容将继续围绕此代码展开,主要讲解spring cloud g ...

  6. Spring Cloud中Feign如何统一设置验证token

    代码地址:https://github.com/hbbliyong/springcloud.git 原理是通过每个微服务请求之前都从认证服务获取认证之后的token,然后将token放入到请求头中带过 ...

  7. Spring Cloud中关于Feign的常见问题总结

    一.FeignClient接口,不能使用@GettingMapping 之类的组合注解 代码示例: @FeignClient("microservice-provider-user" ...

  8. Spring Cloud中的负载均衡策略

    在上篇博客(Spring Cloud中负载均衡器概览)中,我们大致的了解了一下Spring Cloud中有哪些负载均衡器,但是对于负载均衡策略我们并没有去详细了解,我们只是知道在BaseLoadBal ...

  9. Spring Cloud中,Eureka常见问题总结

    Spring Cloud中,Eureka常见问题总结. 1 eureka.environment: 指定环境 参考文档: 1 eureka.datacenter: 指定数据中心 参考文档: 使用配置项 ...

随机推荐

  1. 《手把手教你》系列技巧篇(五十七)-java+ selenium自动化测试-下载文件-下篇(详细教程)

    1.简介 前边几篇文章讲解完如何上传文件,既然有上传,那么就可能会有下载文件.因此宏哥就接着讲解和分享一下:自动化测试下载文件.可能有的小伙伴或者童鞋们会觉得这不是很简单吗,还用你介绍和讲解啊,不说就 ...

  2. 备忘录——基于rdlc报表实现打印产品标签

    目录 0. 背景说明 1. 条形码生成 2. 获取产品的小程序码 3. 报表设计器设计标签模版 3.1 为WinForm控件工具箱添加ReportViewer控件 3.2 为VS2019安装RDLC报 ...

  3. Solon Web 开发,五、数据访问、事务与缓存应用

    Solon Web 开发 一.开始 二.开发知识准备 三.打包与运行 四.请求上下文 五.数据访问.事务与缓存应用 六.过滤器.处理.拦截器 七.视图模板与Mvc注解 八.校验.及定制与扩展 九.跨域 ...

  4. 为什么JavaWeb要分层

    首先bai让我们坐着时光机回到n年前的web开发.那个时候最早du都是静态的html页面,zhi后来有了数据库,有了所谓dao的动态页面,然后程序猿在编码的时候,会把所有的代码都写在页面上,包括数据库 ...

  5. 安卓无法访问Azure服务器和微软API

    Azure服务器保护机制限制移动端访问 必须使用移动app服务来转接api,才可以访问.

  6. 使用Flightradar24's CesiumJS App追踪世界商用航线

    Cesium中文网:http://cesiumcn.org/ | 国内快速访问:http://cesium.coinidea.com/ 每天,超过10万架商业航班在世界各地运送乘客.在任何特定时刻,您 ...

  7. k8S 不同 port 解析

    apiVersion: v1 kind: Service metadata: name: nginx-service spec: type: NodePort // 有配置NodePort,外部流量可 ...

  8. 微服务架构 | 10.1 使用 Sleuth 追踪服务调用链

    目录 前言 1. Sleuth 基础知识 1.1 Sleuth 原理 2. 在服务中使用 Sleuth 追踪 2.1 引入 pom.xml 依赖文件 2.2 查看日志信息 最后 前言 参考资料: &l ...

  9. eslint规则详解

    { // 环境定义了预定义的全局变量. "env": { //环境定义了预定义的全局变量.更多在官网查看 "browser":true, "node& ...

  10. SP5971 LCMSUM - LCM Sum

    一个基于观察不依赖于反演的做法. 首先 \(\rm lcm\) 是不好算的,转化为计算 \(\rm gcd\) 的问题,求: \[\sum\limits_{i = 1} ^ n \frac{in}{\ ...