第十五章:SpringCloud Config 配置手動刷新(了解,自動刷新是關(guān)鍵)

項(xiàng)目一旦放到生產(chǎn)環(huán)境,就需要不停機(jī)更改配置。比如更改一些線程池連接數(shù)什么的。或者是配置文件,這里我演示手動刷新git倉庫上的配置文件

1. 添加pom

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

為什么一定要加actuator依賴呢?

image.png

有了actuator這個(gè)依賴,就可以使用/refresh 這個(gè)節(jié)點(diǎn)來刷新帶有@RefreshScope注解服務(wù)的bean

2. 修改啟動類

添加注解@RefreshScope
注解@RefreshScope拓展:

Refresh Scope
A Spring @Bean that is marked as @RefreshScope will get special treatment when there is a configuration change. This addresses the problem of stateful beans that only get their configuration injected when they are initialized. For instance if a DataSource has open connections when the database URL is changed via the Environment, we probably want the holders of those connections to be able to complete what they are doing. Then the next time someone borrows a connection from the pool he gets one with the new URL.

3. 在貼一下server 和 client 的配置代碼

算了 不貼了,和以前一樣的。
server:
Spring Cloud Config Server
client:
SpringCloud Config Client

啟動config server和 client 服務(wù)

  1. 先來訪問/profile 看服務(wù)是否正常運(yùn)行


  2. 修改git上的application-dev.yml配置


    image.png

    image.png
  3. 再次訪問/profile
    image.png

    我們發(fā)現(xiàn)它并沒有發(fā)生變化。這需要我們的一個(gè)觸發(fā)操作
    發(fā)送一個(gè)post請求給 /refresh
    image.png

    image.png

    再來看看 client端 控制臺打?。?br>
    image.png

    意思是得到刷新指令后,重新從server獲取 配置倉庫的內(nèi)容。

注意!@RefreshScope和 @Configuration在同一類上使用有沖突

@RefreshScope works (technically) on an @Configuration class, but it might lead to surprising behaviour: e.g. it does not mean that all the @Beans defined in that class are themselves @RefreshScope. Specifically, anything that depends on those beans cannot rely on them being updated when a refresh is initiated, unless it is itself in @RefreshScope (in which it will be rebuilt on a refresh and its dependencies re-injected, at which point they will be re-initialized from the refreshed @Configuration).這并不意味著在該類中定義的所有@Beans本身都是@RefreshScope。 具體來說,任何依賴這些bean的東西都不能依賴于它們在刷新時(shí)被更新,除非它本身在@RefreshScope中(在刷新時(shí)它將被重建,并且它的依賴關(guān)系被重新注入,在這一點(diǎn)上它們將被 從刷新的@Configuration重新初始化)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容