Spring Cloud 入门教程(三): 配置自动刷新

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获取的配置。

Spring Cloud 入门教程(三): 配置自动刷新

@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;
    }
}

Spring Cloud 入门教程(三): 配置自动刷新

3). 启动应用, 查看http://localhost:8881/hello

4). 再次修改config-client-dev.properties的内容

hello=Hello World from GIT version 2

5). 用chome的postman发送POST请求:http://localhost/refesh

Spring Cloud 入门教程(三): 配置自动刷新

可以从POST的结果看到,此次refresh刷新的配置变量有hello

6). 再次访问http://localhost/hello,可见到配置已经被刷新

Spring Cloud 入门教程(三): 配置自动刷新

2. 通过Webhook自动触发/refresh方法刷新配置

以上每当GIT中配置文件被修改,仍然需要我们主动调用/refresh方法(手动调用或者写代码调用), 有没有办法让GIT中配置有改动就自动触发客户端的rfresh机制呢? 答案是:有。可以通过GIT提供的githook来监听push命令,如果项目中使用了Jenkins等持续集成工具(也是利用githook来监听的),就可以监听事件处理中直接调用/refresh方法就可以了。

 

 

 

 

 

博客:http://www.cnblogs.com/chry/p/7260778.html