从前几篇文章中我们就可以看出,在分布式系统中,服务数量会很多,如果要修改服务的配置文件,会很麻烦,这个时候,我们想把配置文件放在一个地方统一管理,实时更新,Spring Cloud 就给我们提供了这样一个组件——Spring Cloud Config。
(一)简介
Spring Cloud Config 支持配置文件放在远程仓库中,例如 Git、SVN,也可以挂载到本地。Spring Cloud Config 和 Spring Boot Admin 有一点类似,它也由服务端和客户端组成,即 server、client。
(二)基于 server-client 构建项目
2.1 创建 server
2.1.1 新建一个 module(spring-cloud-config)
2.1.2 pom 文件添加相关依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
2.1.3 启动类添加注解 @EnableConfigServer 开启配置中心的功能
@SpringBootApplication
@EnableConfigServer
public class SpringCloudConfigApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudConfigApplication.class,args);
}
}
2.1.4 添加配置文件
server:
port: 8888
spring:
cloud:
config:
server:
git:
uri: https://github.com/shmilyah/cloud-config-samples.git
search-paths: '{application}'
application:
name: spring-cloud-config
spring.cloud.config.server.git.uri:配置git仓库地址
spring.cloud.config.server.git.searchPaths:配置仓库路径,这里的配置会根据传入的应用名动态查找
由于我这里配置的 git 仓库为公开的,所以不需要配置用户名和密码,如果你配置的是私有仓库,还需要配置用户名和密码
(spring.cloud.config.server.git.username 和 spring.cloud.config.server.git.password)
2.1.5 创建仓库里的配置文件
本例为了测试,我在