Spring Cloud 入门教程(三): 配置自动刷新详解编程语言
之前讲的配置管理, 只有在应用启动时会读取到GIT的内容, 之后只要应用不重启,GIT中文件的修改,应用无法感知, 即使重启Config Server也不行。
比如上一单元(Spring Cloud 入门教程(二): 配置管理)中的Hello World 应用,手动更新GIT中配置文件config-client-dev.properties的内容(别忘了用GIT push到服务器)
hello=Hello World from GIT version 1
刷新 http://locahost/8881/hello,页面内容仍然和之前一样,并没有反映GIT中最新改变, 重启config-server也一样,没有任何变化。要让客户端应用感知到这个变哈, Spring Cloud提供了解决方案是,客户端用POST请求/refresh方法就可以刷新配置内容。
1. 让客户端支持/refresh方法
要让/refresh生效,客户端需要增加一些代码支持:
1). 首先,在pom.xml中添加以下依赖。spring-boot-starter-actuator是一套监控的功能,可以监控程序在运行时状态,其中就包括/refresh的功能。
dependency groupId org.springframework.boot /groupId artifactId spring-boot-starter-actuator /artifactId /dependency
2). 其次,开启refresh机制, 需要给加载变量的类上面加载@RefreshScope注解,其它代码可不做任何改变,那么在客户端执行/refresh的时候就会更新此类下面的变量值,包括通过config client从GIT获取的配置。
@SpringBootApplication @RestController @RefreshScope public class ConfigClientApplication { public static void main(String[] args) { SpringApplication.run(ConfigClientApplication.class, args); @Value("${hello}") String hello; @RequestMapping(value = "/hello") public String hello(){ return hello; }
3). 启动应用, 查看http://localhost:8881/hello
4). 再次修改config-client-dev.properties的内容
hello=Hello World from GIT version 2
5). 用chome的postman发送POST请求:http://localhost/refesh
可以从POST的结果看到,此次refresh刷新的配置变量有hello
6). 再次访问http://localhost/hello,可见到配置已经被刷新
2. 通过Webhook自动触发/refresh方法刷新配置
以上每当GIT中配置文件被修改,仍然需要我们主动调用/refresh方法(手动调用或者写代码调用), 有没有办法让GIT中配置有改动就自动触发客户端的rfresh机制呢? 答案是:有。可以通过GIT提供的githook来监听push命令,如果项目中使用了Jenkins等持续集成工具(也是利用githook来监听的),就可以监听事件处理中直接调用/refresh方法就可以了。
上一篇:Spring Cloud 入门教程(二): 配置管理
下一篇:Spring Cloud 入门教程(四): 分布式环境下自动发现配置服务
参考:
http://www.cnblogs.com/ityouknow/p/6906917.html
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/15343.html
cjavaxml相关文章
- 深度剖析Spring Cloud Alibaba系列——适配Spring Cloud和Nacos的服务元数据
- Spring中优雅的处理全局异常
- Spring Cloud的架构[通俗易懂]
- spring cloud
- Spring Cloud:第三章:Ribbon客服端负载均衡
- Spring Cloud 的微服务架构学习及实践(十六)
- 日常随笔--Spring Cloud、Shell脚本、JDK版本新特征
- 基于Spring Cloud的微服务架构分析
- spring cloud配置熔断器Hystrix及遇到的问题
- spring cloud 配置中心配置哪些东西_druid连接池配置优化
- 微服务治理框架- - -Spring Cloud
- Spring Cloud Tencent 1.9 版本正式发布,大幅提升稳定性
- Spring Cloud 整合 nacos 实现动态配置中心
- Spring Cloud Alibaba 2.2.6发布:新增Nacos注册快速失败的配置
- Spring Cloud Config 配置客户端使用
- Spring Cloud Gateway环境搭建和配置(二)
- 解析Spring Cloud Sleuth的跟踪数据
- Spring Cloud Security配置JWT和OAuth2的集成实现单点登录
- Spring Cloud Security配置JWT和OAuth2的集成实现单点登录-示例
- 配置Spring Cloud Bus并集成消息代理
- 配置Spring Cloud Bus并集成消息代理示例
- Spring Cloud Bus监听服务配置的变化并自动通知其他服务(一)
- Spring Cloud Task查看任务状态示例
- 配置 Spring Cloud Bus 的消息代理示例
- 使用 Spring Cloud Bus 在微服务之间传递消息
- Spring Cloud Data Flow 定义和部署数据流应用程序
- Spring Cloud(二):Spring Cloud Eureka Server高可用注册服务中心的配置详解编程语言
- Docker容器上Spring Cloud微服务相互调用时报错:java.net.UnknownHostException:主机名详解编程语言
- Spring Cloud之Config(配置中心)详解编程语言
- spring架构利器:JFinal MySQL Spring(jfinalmysql)