Spring Cloud Config

对于传统的单体应用,使用配置文件管理所有配置。而在微服务架构中,微服务的配置管理一般有以下需求:

  • 集中管理配置
  • 环境不同,配置不同
  • 运行时可动态调整
  • 配置修改后自动更新

因此对于微服务架构而言,一个通用的配置管理机制必不可少,常见的做法时使用配置服务器管理配置。

Spring Cloud Config简介

Spring Cloud Config为分布式系统提供了集中化的外部配置支持,它分为服务端和客户端两个部分即Config Server和Config Client两部分。由于Config Server和Config Client实现了对Spring Environment和PropertySource抽象的映射, 因此,Spring Cloud Config适合Spring应用程序。

Config Server是一个可横向扩展、集中式的配置服务器即分布式配置中心,它作为一个独立应用,用于集中管理应用程序各个环境下的配置,它可以从配置仓库获取配置信息并提供给客户端使用。

Config Client是Config Server的客户端,通过请求配置中心来获取配置信息,在启动时加载配置并缓存以提高性能。

Spring Cloud Config的配置中心默认采用Git来存储配置信息,因此可以方便地实现对配置的版本控制与内容审计。

image-20220606232213855

Git仓库准备配置信息

新建repo

image-20220607001325420

导入本地

image-20220606235624177

image-20220607001406544

创建borrowservice-dev.yml文件

image-20220606235609117

上传Gitee

image-20220606235723615

创建Config服务端

创建config-server模块

image-20220606233511777

导入依赖

1
2
3
4
5
6
7
8
9
10
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>

添加配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
server:
port: 8601
spring:
application:
name: config-server
cloud:
config:
server:
git: #配置存储配置信息的Git仓库
uri: https://gitee.com/YuanJianWei/springcloud-config.git
username: YuanJianWei
password: 13851176590++
default-label: master
clone-on-start: true #开启启动时直接从git获取配置
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://root:123456@replica1:8005/eureka,
http://root:123456@replica2:8006/eureka

添加启动类

1
2
3
4
5
6
7
8
@SpringBootApplication
@EnableDiscoveryClient
@EnableConfigServer/*启用配置中心功能*/
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}

获取配置信息

获取配置文件信息的访问格式

1
2
3
4
# 获取配置信息
/{label}/{application}-{profile}
# 获取配置文件信息
/{label}/{application}-{profile}.yml

访问http://localhost:8601/master/borrowservice-dev.yml

image-20220607001222532

创建Config客户端

image-20220607002521755

添加依赖

1
2
3
4
5
6
7
8
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>

添加配置文件bootstrap.yml

image-20220607002856093

1
2
3
4
5
6
7
8
spring:
cloud:
config:
name: borrowservice #配置文件名称
uri: http://localhost:8601 #配置服务器地址
profile: prod #环境
label: master #分支

image-20220607003453586

配置中心添加安全认证