SpringCloud Config为微服务架构的微服务提供统一集中的外部配置支持,便于统一管理服务配置。SpringCloud Config分为服务端和客户端两部分。
服务端也就是分布式配置中心,用于连接配置服务器获取配置信息。
客户端是通过配置中心在启动时获取对应业务相关的配置信息。
中文文档:
https://springcloud.cc/spring-cloud-config.html
以下内容是基于上一节的工程,实现SpringCloud Config配置中心和客户端
源码下载:https://github.com/hnyydp/microservice
1、Config Server配置中心创建
(1)、在Github上创建一个microservice-config项目,上传一个配置文件mircoservice-application.yml
spring:
profiles: dev
hello: hello-dev
---
spring:
profiles: prod
hello: hello-prod
(2)、新建一个microservice-config-server-7001
服务,添加SpringCloud Config Server依赖:
<!-- springcloud config server-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
(3)、添加配置信息application.yml
server:
context-path: /
port: 7001
spring:
application:
name: microservice-config-server
cloud:
config:
label: master #配置仓库的分支
server:
git:
uri: https://github.com/hnyydp/microservice-config.git #配置git仓库地址
#search-paths: microservice-config/src/main/resources/properties #配置仓库路径
##访问git仓库的用户名密码 公共仓库可以不写,私有仓库需要写
#username: xxx
#password: xxx
(4)、在主启动类ConfigServerApplication_7001中添加@EnableConfigServer
@EnableConfigServer //开启Config配置中心
@SpringBootApplication
public class ConfigServerApplication_7001 {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication_7001.class, args);
}
}
(5)、启动服务,分别访问http://localhost:7001/mircoservice-application-dev.yml,http://localhost:7001/mircoservice-application-prod.yml,如果能获取到配置信息,则说明配服务端置中心启动成功。
可以通过多种方式访问资源,Http请求地址和资源文件映射如下:
/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties
2、Config客户端创建
(1)、新建一个microservice-config-client-7002
服务,添加SpringCloud Config Client依赖:
<!-- springcloud config -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-client</artifactId>
</dependency>
(2)、添加配置信息bootstrap.yml
,注意配置文件名是boostrap,他是系统级别配置,比application用户级别配置的优先级更高,可以同时存在。
server:
port: 7002
spring:
application:
name: microservice-config-client
cloud:
config:
name: mircoservice-application #github上读取资源名称
profile: prod #环境
label: master #远程仓库的分支
uri: http://localhost:7001/ #服务配置中心的网址
(3)、编写API接口”/hello”,返回从配置中心读取的spring.hello的值
@RestController
@SpringBootApplication
public class ConfigClientApplication_7002 {
public static void main(String[] args) {
SpringApplication.run(ConfigClientApplication_7002.class, args);
}
@Value("${spring.hello}")
private String hello;
@RequestMapping("/hello")
public String hello() {
return hello;
}
}
(4)、启动配置中心,启动该服务,访问localhost:7002/hello,变更配置中的环境profile,返回如下结果,说明SpringCloud Config客户端应用成功。