扯淡:
【上一章】已经将微服务的配置文件托管到git上,服务启动的时候会通过config server拉取远程git仓库对应的文件加载自己的配置。本章将介绍刷新配置文件。
个人学习总结:
链接:【springboot、springcloud、docker 等,学习目录】
问题:当修改了远程的配置文件,微服务怎么知道自己的配置被修改,需要重启吗?
refresh 使用:
修改了远程配置文件,对应的微服务是不会知道自己的配置文件被修改,springcloud中让客户端(微服务)自己去访问/refresh请求去感知自己配置文件的变化。本节将继续使用用户微服务作修改。
1、pom依赖:
<!-- 提供监控功能 此处引入是需要refresh 的功能 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
actuator的starter会监控正在运行的程序,包含了refresh功能。
2、远程配置文件添加自定义配置:
此自定义配置仅仅用作测试刷新。
3、修改UserController:
// 当配置中心配置刷新,自动将服务对应的新配置更新到此...
@RefreshScope
@RestController
@RequestMapping(value = "/user")
public class UserController {
@Autowired
private UserService userService;
@Value("${sms}")
private String sms;
@RequestMapping("getRefreshTest")
public String getRefreshTest(){
return sms;
}
.
.
.
}
4、修改application.yml:
springboot2.0 之后默认没有开启/refresh,需自己配置添加。
# 配置刷新
management:
endpoints:
web:
exposure:
include: refresh
在application.yml中配置,但是它在远程的git中管理,所以我直接添加到本地的bootstrap.yml中。因为bootstrap 优先 application 加载,建议默认不会再次修改的配置加到bootstrap中,其他配置加到远程的application.yml中。
5、测试:
5.1、启动Eureka、配置中心、用户微服务。
5.2、请求:127.0.0.1:8081/user/getRefreshTest
5.3、修改远程配置文件sms字段值:
5.4、手动刷新配置:
请求接口:http://127.0.0.1:8081/actuator/refresh
5.5、再次请求:127.0.0.1:8081/user/getRefreshTest
可见:sms 字段的信息由"how`s it going! Ron" 变为了“It`s not bad!”,而这一过程中没有重启任何服务器,修改远程配置文件后仅仅请求了微服务的http://127.0.0.1:8081/actuator/refresh 接口。
至此,springcloud的refresh 刷新功能完成。
总结:
1、添加依赖,actuator会监控程序运行的状态。
2、springboot2.0默认没有开启refresh端点,需配置。
3、每个客户端都有自己的刷新端点/actuator/refresh。
4、@RefreshScope所注解的类会感知到配置刷新,并将感知作用到对应字段。
代码地址:
https://gitee.com/cpla026/springcloud/tree/master/springcloud_parent/springcloud_user_bus
个人学习分享
更多 springboot、springcloud、docker 文章,关注微信公众号吧: