Spring Cloud Config提供了一种在分布式系统中外部化配置服务器和客户端的支持。配置服务器有一个中心位置,管理所有环境下的应用的外部属性。客户端和服务器映射到相同Spring Eventment 和 PropertySrouce抽象的概念,所以非常适合Spring应用,但也可以在任何语言开发的任何应用中使用。在一个应用从开发、测试到生产的过程中,你可以分别地管理开发、测试、生产环境的配置,并且在迁移的时候获取相应的配置来运行。

准备工作

准备几个配置文件,命名规范为 项目名称-环境名称.yml。本文在git仓库:https://github.com/xuwenjin中,新建目录config-repo-xwj,创建以下几个文件:

每个文件内容如下:

application.yml

  1. profile: profile-default

config-client.yml

  1. profile: config-client

config-client-dev.yml

  1. profile: dev

config-client-test.yml

  1. profile: test

代码示例

创建一个Maven项目,在pom.xml文件中添加如下内容:

  1. <dependencyManagement>
  2. <dependencies>
  3. <dependency>
  4. <groupId>org.springframework.cloud</groupId>
  5. <artifactId>spring-cloud-dependencies</artifactId>
  6. <version>Edgware.SR4</version>
  7. <type>pom</type>
  8. <scope>import</scope>
  9. </dependency>
  10. </dependencies>
  11. </dependencyManagement>
  12.  
  13. <dependencies>
  14. <dependency>
  15. <groupId>org.springframework.cloud</groupId>
  16. <artifactId>spring-cloud-config-server</artifactId>
  17. </dependency>
  18. <dependency>
  19. <!-- 解决启动报Caused by: java.lang.ClassNotFoundException: org.eclipse.jgit.api.TransportConfigCallback -->
  20. <groupId>org.eclipse.jgit</groupId>
  21. <artifactId>org.eclipse.jgit</artifactId>
  22. <version>4.9.0.201710071750-r</version>
  23. </dependency>
  24. </dependencies>

启动类:

  1. @SpringBootApplication
  2. @EnableConfigServer // 通过@EnableConfigServer注解激活配置服务
  3. public class ConfigServerApplication {
  4.  
  5. public static void main(String[] args) {
  6. SpringApplication.run(ConfigServerApplication.class, args);
  7. }
  8.  
  9. }

配置文件:application.yml

  1. server:
  2. port:
  3.  
  4. spring:
  5. application:
  6. name: config-server #应用程序名称
  7. cloud:
  8. config:
  9. server:
  10. git:
  11. uri: https://github.com/xuwenjin/config-repo-xwj #git上,配置文件地址

这样,一个Config Server就完成了。

测试工作

规则中的参数含义如下:

  • {application}映射到客户端的“spring.application.name”(项目名称)
  •  {profile}映射到客户端上的“spring.profiles.active”(环境名称)
  •  {label}这是一个服务器端功能,标记“版本”的配置文件集(在git中,相当于分支名)

启动服务,也可以看到匹配规则:

先试下 {application}/{profile}[/{label}] 这个规则,请求路径是 http://localhost:18083/config-client/dev/master,返回了所有配置文件信息:

另外四种规则差不多,可使用以下路径来访问config-client-dev.yml文件,并直接返回其中的内容:

http://localhost:18083/config-client-dev.yml

http://localhost:18083/master/config-client-dev.yml

http://localhost:18083/config-client-dev.properties

http://localhost:18083/master/config-client-dev.properties

如果想要访问config-client-test.yml文件,只需要将上面的 dev 换成 test 就行。

但是如果匹配不上呢?结果如下:

可以看到,当匹配不上时,会默认读取application.yml文件。

Config Server服务端是支持热加载的,即不重启服务的情况下更改配置文件信息,是可以直接读取的

源码分析

当发送请求时(如:http://localhost:18083/master/config-client-dev.yml ),会在 EnvironmentController 中进行匹配。如下:

  1. @RestController
  2. @RequestMapping(method = RequestMethod.GET, path = "${spring.cloud.config.server.prefix:}")
  3. public class EnvironmentController {
  4.  
  5. private EnvironmentRepository repository;
  6.  
  7. // ...
  8.  
  9. @RequestMapping({ "/{label}/{name}-{profiles}.yml", "/{label}/{name}-{profiles}.yaml" })
  10. public ResponseEntity<String> labelledYaml(@PathVariable String name, @PathVariable String profiles,
  11. @PathVariable String label, @RequestParam(defaultValue = "true") boolean resolvePlaceholders)
  12. throws Exception {
  13. // 校验profiles是否含义"-",如果有则抛出异常
  14. validateProfiles(profiles);
  15. // 获取环境信息,即远程配置文件数据
  16. Environment environment = labelled(name, profiles, label);
  17. // 将environment对象转为Map
  18. Map<String, Object> result = convertToMap(environment);
  19. if (this.stripDocument && result.size() == && result.keySet().iterator().next().equals("document")) {
  20. Object value = result.get("document");
  21. if (value instanceof Collection) {
  22. return getSuccess(new Yaml().dumpAs(value, Tag.SEQ, FlowStyle.BLOCK));
  23. } else {
  24. return getSuccess(new Yaml().dumpAs(value, Tag.STR, FlowStyle.BLOCK));
  25. }
  26. }
  27. String yaml = new Yaml().dumpAsMap(result);
  28.  
  29. if (resolvePlaceholders) {
  30. yaml = resolvePlaceholders(prepareEnvironment(environment), yaml);
  31. }
  32.  
  33. return getSuccess(yaml);
  34. }
  35.  
  36. // ...
  37.  
  38. }

核心方法 labelled 中,会调用最核心的类 NativeEnvironmentRepositor 的 findOne 方法:

  1. @RequestMapping("/{name}/{profiles}/{label:.*}")
  2. public Environment labelled(@PathVariable String name, @PathVariable String profiles,
  3. @PathVariable String label) {
  4. if (name != null && name.contains("(_)")) {
  5. // "(_)" is uncommon in a git repo name, but "/" cannot be matched
  6. // by Spring MVC
  7. name = name.replace("(_)", "/");
  8. }
  9. if (label != null && label.contains("(_)")) {
  10. // "(_)" is uncommon in a git branch name, but "/" cannot be matched
  11. // by Spring MVC
  12. label = label.replace("(_)", "/");
  13. }
  14. Environment environment = this.repository.findOne(name, profiles, label);
  15. return environment;
  16. }

findOne方法会从远程git仓库中获取配置文件数据:

  1. @Override
  2. public Environment findOne(String config, String profile, String label) {
  3. SpringApplicationBuilder builder = new SpringApplicationBuilder(
  4. PropertyPlaceholderAutoConfiguration.class);
  5. ConfigurableEnvironment environment = getEnvironment(profile);
  6. builder.environment(environment);
  7. builder.web(false).bannerMode(Mode.OFF);
  8. if (!logger.isDebugEnabled()) {
  9. builder.logStartupInfo(false);
  10. }
  11. String[] args = getArgs(config, profile, label);
  12. // 设置监听器
  13. builder.application()
  14. .setListeners(Arrays.asList(new ConfigFileApplicationListener()));
  15. ConfigurableApplicationContext context = builder.run(args);
  16. environment.getPropertySources().remove("profiles");
  17. try {
  18. return clean(new PassthruEnvironmentRepository(environment).findOne(config,
  19. profile, label));
  20. }
  21. finally {
  22. context.close();
  23. }
  24. }

获取的Environment对象,数据结构如下:

可以看到,配置文件信息,会放在 PropertySources 对象中~

spring cloud config服务器的更多相关文章

  1. Spring Cloud官方文档中文版-Spring Cloud Config(上)

    官方文档地址为:http://cloud.spring.io/spring-cloud-static/Dalston.SR2/#spring-cloud-feign 文中例子我做了一些测试在:http ...

  2. 介绍一下Spring Cloud Config

    Spring Cloud Config为分布式系统中的外部配置提供服务器和客户端支持.使用Config Server,您可以在所有环境中管理应用程序的外部属性.客户端和服务器上的概念映射与Spring ...

  3. spring cloud config客户端

    上篇介绍了spring cloud config服务器,本篇介绍客户端.客户端主要是从config服务器获取配置信息. 代码示例 首先创建一个Maven项目,在pom.xml文件中添加依赖: < ...

  4. Spring Cloud Config中文文档

    https://springcloud.cc/spring-cloud-config.html 目录 快速开始 客户端使用 Spring Cloud Config服务器 环境库 健康指标 安全 加密和 ...

  5. Spring Cloud官方文档中文版-Spring Cloud Config(上)-服务端(配置中心)

    官方文档地址为:http://cloud.spring.io/spring-cloud-static/Dalston.SR2/#spring-cloud-feign 文中例子我做了一些测试在:http ...

  6. 9.Spring Cloud Config统一管理微服务配置

    Spring Cloud Config统一管理微服务配置 9.1. 为什么要统一管理微服务配置 9.2. Spring Cloud Config简介 Spring Cloud Config为分布式系统 ...

  7. Spring Cloud Config教程(四)快速开始

    Spring Cloud Config为分布式系统中的外部配置提供服务器和客户端支持.使用Config Server,您可以在所有环境中管理应用程序的外部属性.客户端和服务器上的概念映射与Spring ...

  8. Spring Cloud官方文档中文版-Spring Cloud Config(下)-客户端等

    官方文档地址为:http://cloud.spring.io/spring-cloud-static/Dalston.SR2/#_serving_alternative_formats 文中例子我做了 ...

  9. 搭建spring cloud config

    很久没更新了,因为不是专职研究spring cloud,因此更新速度得看工作强度大不大,每天能抽出的时间不多,如果更新太慢了,并且有小伙伴看的话,请见谅了. Spring Cloud简介 Spring ...

随机推荐

  1. IT资产管理—采购与合同管理功能

  2. Localization

    Localization (using Histogram Filters) 定位指的是在传感器和移动之间来回的迭代,使得能够保持跟踪目标对象的位置.方向和速度. 这篇将写一个程序来实施定位,与GPS ...

  3. kali安装配置ftp

    参考:https://zhidao.baidu.com/question/1511146077646448900.html 一)安装 1.用sudo apt-get install 下载安装包

  4. noip第23课资料

  5. 从MATLAB到FPGA 视频和图像处理——讲座学习小结(视频地址https://ww2.mathworks.cn/videos/from-matlab-to-fpga-video-and-image-processing-102492.html)

    1.HDLcoder产品介绍 图像处理分为两个部分: 这里主要讨论第一部分图像处理部分. 一般产品设计流程如下: 适用人群有以下两类: 这里先用一张slider来进行整体概括: 基于模型的设计的好处— ...

  6. kmp循环节

    循环判断   i%(i-next[i]) == 0 && next[i] != 0 循环长度  i-next[i];

  7. Django View 进阶

    返回404 from django.http import HttpResponse, HttpResponseNotFound def not_found(request): ) 或 return ...

  8. git & github 同步文件

    step1 : 在github上建立一个 repository https://github.com/ntu-juking/softwaretesting.git repository name is ...

  9. iOS逆向之TheOS

    TheOS 被设计为一个在基于 Unix 平台 (Mac OS X.IOS…) 和大多数 的Linux 平台下开发 iOS 程序的集成开发环境.说是集成开发环境,其实就是给我们准备好了一些代码模板.预 ...

  10. Swift5 语言指南(十一) 结构和类

    结构和类是通用的,灵活的结构,它们成为程序代码的构建块.您可以使用与定义常量,变量和函数相同的语法来定义属性和方法,以便为结构和类添加功能. 与其他编程语言不同,Swift不要求您为自定义结构和类创建 ...