一 为什么要使用统一配置管理
对于传统的单体应用,一般使用的都是配置文件进行配置管理,并在应用启动的时候通过指定 profile 去加载不同的配置文件。在微服务的架构中,对于微服务的配置管理一般会有以下的需求:
- 集中管理配置:一个微服务架构的系统会有非常多的服务,对每个服务的配置文件进行统一管理是非常有必要的
- 不同环境不同配置
- 运行期间动态调整
- 配置修改后可自动更新
二 Spring Cloud Config 简介
Spring Cloud Config 为分布式系统外部化配置提供了服务端和客户端的支持,它包含了 Config Server 和 Config Client 两部分
Config Server 是一个可横向 拓展、集中式的配置服务器,用于集中管理应用程序各个环境下的配置,默认使用 Git 存储配置内容
Config Client 是 Config Server 的客户端,用于操作存储在 Config Server 中的配置属性。当各个服务启动时,会请求 Config Server 以获取所需要的配置属性
三 编写 Config Server
1 创建一个 Git 仓库并上传,并创建几个配置文件
microservice-foo.yml
microservice-foo-dev.yml
microservice-foo-test.yml
microservice-prodcution.yml
2 创建一个项目(config-server)
添加依赖
compile group: 'org.springframework.cloud', name: 'spring-cloud-config-server', version:'1.4.0.RELEASE'
编写启动类
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
3 编写配置文件 application.yml
server:
port: 8080
spring:
application:
name: microservice-config-server
cloud:
config:
server:
git:
uri: # 配置Git仓库的地址
username: # Git仓库的账号
password: # Git仓库的密码
4 访问不同配置文件
Config Server 的端点
/{application}-{profile}.yml
/{lable}/{application}-{profile}.yml
其中{application}代表服务的名称,{label} 对应的是 仓库的分支,可以直接通过url进行访问:http://localhost:8080/microservice-foo-dev.yml
四 编写 Config Client
1 创建一个新项目(config-client),并添加相关依赖
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version:'1.5.9.RELEASE'
compile group: 'org.springframework.cloud', name: 'spring-cloud-starter-config', version:'1.4.0.RELEASE'
2 编写配置文件application.yml
server:
port: 8081
3 创建配置文件bootstrap.yml
spring:
application:
name: microservice-foo # 对应config server所获取的配置文件的{application}
cloud:
config:
uri: http://localhost:8080/
profile: dev # profile对应config server所获取的配置文件中的{profile} ,多个可以使用,分割
label: master # 指定Git仓库的分支,对应config server所获取的配置文件的{label}
其中:
- spring.application.config.url 默认值是
http://locahost:8888
- bootstrap.yml 中的配置信息如果和 application.yml 中的配置信息重复,将会覆盖掉 application.yml 中的。如果不想要覆盖,可以设置
spring.cloud.bootstrap.enabled
为false
五 Spring Cloud Config 与 Eureka 配置使用
将 Config Server 和 Config Client 同时加入到 Eureka 中。
修改 Config Client 的 bootstrap.yml 中的配置,使得 Config Client 可以直接通过 Config server 的名称获取获取到配置信息
spring:
application:
name: microservice-foo # 对应config server所获取的配置文件的{application}
cloud:
config:
profile: dev
label: master
discovery:
enabled: true # 表示使用服务发现组件中的Config Server,而不自己指定Config Server的uri,默认false
service-id: microservice-config-server-eureka # 指定Config Server在服务发现中的serviceId,默认是configserver
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/