上篇介绍了spring cloud config服务器,本篇介绍客户端。客户端主要是从config服务器获取配置信息。html
代码示例git
首先建立一个Maven项目,在pom.xml文件中添加依赖:web
<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>
增长一个Controller,用于测试请求:spring
@RestController public class IndexController { @Value("${profile}") private String profile; @RequestMapping("/profile") public String getProfile() { return profile; } }
配置文件:bootstrap.ymlbootstrap
spring: application: name: config-client cloud: config: uri: http://localhost:18083 #更改配置服务器的位置,默认地址是http://localhost:8888 profile: test #对应spring.profiles.active label: master #分支名。当配置服务器是git时,默认是master
配置文件:application.yml安全
server: port: 18084
启动服务,能够看到会请求http://localhost:18083,即从config server获取配置信息。也会打印出environment对象的值,即name(项目名称)、profiles(环境名称)、label(分支名称)。以下所示:服务器
测试工做:app
请求路径:http://localhost:18084/profile,测试结果:spring-boot
若是要获取config-client-dev.yml文件中的内容,只须要改spring.cloud.config.profile: dev就行工具
配置内容的热加载:
若是不重启应用,可以作到配置的刷新吗?答案显然是能够的。
一、增长actuator依赖,暴露/refresh端点:
<dependency> <!-- 监控管理(如:状态页和健康指标) --> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
二、在上面的IndexController中增长@RefreshScope注解:
@RestController @RefreshScope // 这边的@RefreshScope注解不能少,不然即便调用/refresh,配置也不会刷新 public class IndexController { @Value("${profile}") private String profile; @RequestMapping("/profile") public String getProfile() { return profile; } }
三、咱们将config-client-test.yml中值改成
profile: abcd
并提交到git仓库
四、使用Postman(也可使用其它工具)请求:
POST http://localhost:18084/refresh
请求结果是:
[ "config.client.version", "profile" ]
最后再次访问http://localhost:18084/profile,将会看到返回值是 abcd,说明配置已刷新。配置自动刷新可参考:使用spring cloud bus自动刷新配置
遇到的坑:若是spring cloud使用的版本是 Edgware 以及以前,须要关掉actuator安全,把 manage.security.enabled 设为false
总结
一、spring cloud配置加载顺序: 加载bootstrap.* 配置 --> 链接config-server,加载远程配置 --> 加载application.* 配置
二、远程配置优先级高于本地配置,application.*会覆盖bootstrap.*中的配置
三、若是在远程配置中找不到匹配配置文件,则默认找远程的application.*文件
四、若是config客户端不配置项目名称,则会使用默认的项目名称(即application),也会查找远程的application.*文件
五、通常将不太会改变的配置放在bootstrap.*文件中,如spring.application.name