1. 程式人生 > >Spring Cloud 入門教程(三): 配置自動刷新

Spring Cloud 入門教程(三): 配置自動刷新

入門 stc pro 解決方案 con log clas ring color

之前講的配置管理, 只有在應用啟動時會讀取到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 入門教程(二): 配置管理

參考:

http://www.cnblogs.com/ityouknow/p/6906917.html

Spring Cloud 入門教程(三): 配置自動刷新