以前讲的配置管理, 只有在应用启动时会读取到GIT的内容, 以后只要应用不重启,GIT中文件的修改,应用没法感知, 即便重启Config Server也不行。html
好比上一单元(Spring Cloud 入门教程(二): 配置管理)中的Hello World 应用,手动更新GIT中配置文件config-client-dev.properties的内容(别忘了用GIT push到服务器)git
hello=Hello World from GIT version 1
刷新 http://locahost/8881/hello,页面内容仍然和以前同样,并无反映GIT中最新改变, 重启config-server也同样,没有任何变化。要让客户端应用感知到这个变哈, Spring Cloud提供了解决方案是,客户端用POST请求/refresh
方法就能够刷新配置内容。spring
1. 让客户端支持/refresh方法服务器
要让/refresh生效,客户端须要增长一些代码支持:app
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获取的配置。spring-boot
@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的内容post
hello=Hello World from GIT version 2
5). 用chome的postman发送POST请求:http://localhost/refeshurl
能够从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