Spring Cloud Config

126 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第1天

Spring Cloud Config

快速入门

Spring Cloud Config 用来为分布式系统中的基础设施和微服务应用提供集中化的外部配置支持,分为服务端和客户端两部分。

服务端:分布式配置中心,是一个独立的微服务应用,用来连接配置仓库并为客户端提供获取配置信息、加密/解密信息等访问接口;

客户端:是微服务架构中的各个微服务应用或基础设施,通过指定的配置中心来管理应用资源与业务相关的配置内容,并在启动的时候从配置中心获取和加载配置信息。

配置信息:Spring Cloud Config配置中心默认采用Git存储配置信息,天然支持对微服务应用配置信息的版本管理。

构架配置中心

pom

@EnableConfigServer

yaml

# 配置Git仓库位置
spring.cloud.config.server.git.uri=https://github.com/liangmeyu/
# 配置仓库路径下的相对搜索位置,可以配置多个。
spring.cloud.config.server.git.search-paths=spring_cloud_config_repo
# 访问Git仓库的用户名
spring.cloud.config.server.git.username=There
# 防伪Git仓库的密码。
spring.cloud.config.server.git.password=Once

服务端通过git clone命令将配置内容复制一份在本地存储,然后读取这些内容并返回给微服务应用进行加载。

配置规则

  • /{application}/{profile}[/{label}]
  • /{application}-{profile}.yml
  • /{label}/{application}-{profile}.yml
  • /{application}-{profile}.properties
  • /{label}/{application}-{profile}.properties

客户端配置映射

pom

bootstrap.properties

# 配置文件规则中的{application}部分
spring.application.name=spring-cloud-client-su
# 配置文件规则中的{profile}部分
spring.cloud.config.profile=dev
# 配置文件规则中的{label}部分
spring.cloud.config.label=master
# 配置中心Config Server的地址
spring.cloud.config.uri=http://localhost:1234

服务端基础架构

远程Git仓库:用来存储配置文件

Config Server:指定要连接的Git仓库位置以及账户、密码等连接信息。

本地Git仓库:用来存储配置文件(缓存)

Config Client:指定Config Server的地址,实现应用启动时从外部获取应用需要的配置信息。

客户端获取配置信息

  1. 应用启动是,根据bootstrap.properties配置信息,从Config Server获取配置信息。
  2. Config Server根据Git仓库信息和Config Client请求信息查找并返回配置信息
  3. 通过git clone命令下载配置信息到Config Server的文件系统中。

加载顺序

  1. 命令行参数
  2. SPRING_APPLICATION_JSON
  3. java:comp/env中的JNDI属性
  4. 系统属性 System.getProperties()
  5. 环境变量
  6. random.*随机属性
  7. 应用jar包之外,profile环境
  8. 应用jar包之内,profile环境
  9. 应用jar包之外,yaml
  10. 应用jar包之内,yaml
  11. @PropertySource
  12. SpringApplication.setDefaultProperties