在项目多了以后,我们需要一个配置中心来统一管理配置文件,spring cloud config应运而生。
spring cloud config
配置文件
在git上新建文件夹repo_configs;新增配置文件
- fooservice-dev.yml
- fooservice-pro.yml
- fooservice-test.yml
内容为:
1 | hello: |
spring cloud config server
新建项目config.center
- 添加依赖
1 | <dependency> |
- 修改配置文件
1 | server: |
- 启动类添加注解 @EnableConfigServer
1 | @SpringBootApplication |
启动查看抓取是否成功
路径转换规则
仓库中的配置文件会被转换成web接口,访问可以参照以下的规则:
1 | /{application}/{profile}[/{label}] |
spring cloud config client
修改producer项目
添加依赖
1
2
3
4<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-client</artifactId>
</dependency>添加配置文件
需要添加 bootstrap.yml , spring cloud config 默认会从中读取相关信息。
1 | spring: |
- 注解
无需添加额外注解
- 新增接口以测试
1 | @Value("${hello.msg}") |
- 测试
spring cloud config 高可用
为 spring cloud config server 集群使用注册中心 eureka
spring cloud config server
- 添加依赖
1 | <dependency> |
- 修改配置文件
1 | server: |
为启动类添加注解 @EnableDiscoveryClient
启动,在eureka控制台查看,可以看到config center已经注册到了eureka
spring cloud config client
- 配置文件
修改 bootstrap.yml
1 | spring: |
enruka配置等从 application.yml 移至 bootstrap.yml
- 启动验证
refresh
在启动producer后,如果更改了配置文件,producer内仍然是启动时的值,现在改造producer让它更改配置文件后刷新。
- 添加依赖
1 | <dependency> |
- 暴露refresh接口
在application.yml中添加
1 | management: |
- 添加需要refresh的类
在 HelloController 上添加注解 @RefreshScope
1 | @RestController |
启动验证
- 访问 http://localhost:8998/hello/say/hello , 显示内容为 hello dev;
- 更新 git 文件 fooservice-dev.yml , 内容修改为 hello dev 1
- Post 访问 http://localhost:8998/actuator/refresh( eg:curl -X POST http://localhost:8998/actuator/refresh)
- 再次访问 http://localhost:8998/hello/say/hello, 内容已更改为 hello dev 1
spring cloud bus
在更新配置后,如果有多个项目,每个项目都得访问一次refresh接口。spring cloud bus 可以让我们从这个重复的劳动中解放出来。
spring cloud bus需要mq的支持,mq需要支持acmq协议或者使用kafka。
这里使用rabbit mq。
对应用进行改造
- 添加依赖
1 | <dependency> |
- 添加rabbit mq配置
在application.yml中添加mq配置
1 | spring: |
对config server改造
- 添加依赖
1 | <dependency> |
- 修改配置文件
暴露bus-refresh接口,添加mq配置。
1 | management: |
验证
启动config center,并分别使用8998,8999端口启动producer;
访问 http://localhost:8998/hello/say/hello,http://localhost:8999/hello/say/hello;显示信息 hello dev 1;
更新git上的配置文件,内容为 hello dev bus update;
curl -X POST http://localhost:8011/actuator/bus-refresh 手动触发bus事件(如果配置了git的wenbook则自动触发)
再次访问 http://localhost:8998/hello/say/hello,http://localhost:8999/hello/say/hello;显示信息 hello dev bus update,成功更新配置