为什么要统一管理微服务配置
对于传统的单体应用。经常使用一个配置文件管理所有配置。如果需要切换环境,就修改配置文件的profile。但是对于微服务多个应用来说,配置文件过多修改起来非常不方便。这时候,就需要一个通用的微服务配置管理。常见的做法就是使用一个配置服务器管理配置。
Spring Cloud Config 简介
Spring cloud,config为分布式系统外部化配置提供了服务端和客户端的支持。它包括config server和config client两部分。
Config server是一个可横向扩展、集中式的配置服务器,它用于集中管理应用程序各个环境下的配置,默认使用git存储配置内容。因此可以很方便地实现对配置的版本控制和内容审计。
Config client是conflicts server的客户端,用于操作存储在config server中的配置属性。
编写 Config Server
在git仓库新建四个文件。格式是{application}-{profile}.properties
,.yml
也可以。
内容分别是
profile = default-1.0
profile = dev-1.0
profile = prod-1.0
profile = test-1.0
创建一个maven项目。加入config-server
的依赖。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
启动类添加注解@EnableConfigServer
,声明是一个Config Server。
配置文件application.yml
。
server:
port: 8011
spring:
cloud:
config:
server:
git:
uri: https://gitee.com/weiwei333/spring-cloud-config-repo
username: your git account # git或者gitee的用户名
password: your git password # git或者gitee的登录密码
application:
name: config-server
完成。访问http://localhost:8011/config/dev
。
laber为null,表示默认是master。分支名。
还可以访问具体的配置文件名。如:http://localhost:8011/config-dev.properties
编写 Config Client
创建一个maven工程,添加pom依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
配置文件配置
server:
port: 8012
然后新建一个bootstrap.yml
配置文件。为什么要新建一个配置文件?
因为 Spring Cloud 有一个引导上下文的概念,引导上下文负责从配置服务器加载配置属性,以及解密外部配置文件的属性。他的配置和主程序的配置文件不同,引导上下文加载bootstrap.*中的配置,且优先级更高。
spring:
application:
name: config # 这个地方对应的是配置文件的 {application}
cloud:
config:
uri: http://localhost:8011
profile: dev
label: master
编写一个controller来获取配置。
@RestController
public class ConfigClientController {
@Value("${profile}")
private String profile;
@RequestMapping("/profile")
public String getConfig(){
return this.profile;
}
}
访问 http://localhost:8012/profile
。可以获得配置。
说明Config Client 已经可以正常的获取Config Server的配置了。