一、 Spring Cloud Config简介
微服务要实现集中管理微服务配置、不同环境不同配置、运行期间也可动态调整、配置修改后可以自动更新的需求,Spring Cloud Config同时满足了以上要求。Spring Cloud Config 分为Config Server和Config Client两部分,是一个可以横向扩展,集中式的配置服务器, 默认使用Git存储配置内容。
Spring Cloud Config 原理图如图所示:
-
二、创建Server端
代码以springcloud-03-config为例:https://github.com/shinians/springcloud-demos
1.先在github上新建一个仓库,添加配置文件。
limp-config-dev.yml 文件内容如下
limp: hello: hello springcloud dev config
2.pom引入
org.springframework.bootspring-boot-starter-weborg.springframework.cloudspring-cloud-starter-config-server
3.在程序的入口Application类加上@EnableConfigServer注解开启配置服务器的功能,代码如下:
3.需要在程序的配置文件application.yml文件配置以下
spring: cloud: config: server: git: uri: https://github.com/shinians/spring-cloud-demo-config #username: #password: #search-paths: test-CONFIG application: name: spring-cloud-config-server-007server: port: 7002
spring.cloud.config.server.git.uri:配置git仓库地址
spring.cloud.config.server.git.searchPaths:配置仓库路径
spring.cloud.config.label:配置仓库的分支
spring.cloud.config.server.git.username:访问git仓库的用户名
spring.cloud.config.server.git.password:访问git仓库的用户密码
如果Git仓库为公开仓库,可以不填写用户名和密码,如果是私有仓库需要填写。
启动后我们可以访问下
服务端启动成功
http请求地址和资源文件映射如下:
/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties
三:构建客端
pom引入
org.springframework.bootspring-boot-starter-weborg.springframework.cloudspring-cloud-starter-config
配置文件bootstrap.yml
读取配置文件种的信息
Controller
测试
客户端成功获取配置信息(完成)
End:
例子很简单,像自动刷新、结合bus、配置数据库和公用配置会在之后的章节介绍。
更多信息可以关注今日头条@架构师速成记