spring cloud 配置文件熱加載--@RefreshScope

spring cloud項目中,如果想要使配置文件中的配置修改後不用重啓項目即生效,可以使用@RefreshScope配置來實現

 

1、添加Maven依賴

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

2、在配置類上加@RefreshScope註解,引入配置@Value

 
@Component
@RefreshScope
public class OtherConfig {
    /**是否需要保存切圖*/
    @Value("${is.cut.save:false}")
    private String isCutSave;
 
    /**保存切圖位置*/
    private static String cutSavePath;
 
    /** 靜態字段賦值 */
    @Value("${cut.save.path:/server/files}")
    public void setCutSavePath(String cutSavePath) {
        OtherConfig.cutSavePath = cutSavePath;
    }
 
    public String getCutSavePath() {
        return cutSavePath;
    }
 
    public String getIsCutSave() {
        return isCutSave;
    }
 
    public void setIsCutSave(String isCutSave) {
        this.isCutSave = isCutSave;
    }
}

 

 tips:1.@Value給靜態變量賦值,不能直接寫在變量上,應該放在變量的set()方法上,且該方法不能被static修飾。其中需要在類上加入@Component註解。

     2.通過@Value(“${xxxx}”)可以獲取屬性文件中對應的值,但是如果屬性文件中沒有這個屬性,則會報錯。可以通過賦予默認值解決這個問題,如@Value("${xxxx:yyyy}")

 

3、配置文件

 
# 動態刷新配置--忽略權限攔截
management.security.enabled=false
 
# 是否需要保存切圖
is.cut.save=false
 
# 保存切圖位置
cut.save.path=/server/files

4、如果採用了consul配置中心:bootstrap.properties新增配置項

spring.cloud.consul.config.watch.enabled=true

項目啓動後,更改註冊中心配置,等待大約一秒後配置即可生效

 

5.1、如果採用的是本地配置文件:發送刷新請求

curl -X POST http://localhost:8080/refresh

management.security.enabled配置爲false後,項目啓動時可以在啓動日誌中發現下行日誌,表明/refresh請求可用。我們修改配置文件後,調用該請求即可通知服務刷新配置,配置就生效了,無需重啓項目。

 

5.2、在Spring Boot升級到2.0.3.RELEASE後需新增配置,此時刷新配置文件url爲:http://localhost:8080/actuator/refres

management.endpoints.web.exposure.include=refresh

參考資料:

1.Spring Cloud Consul實時動態更新配置:https://blog.csdn.net/fomeiherz/article/details/103525020?utm_medium=distribute.pc_relevant.none-task-blog-title-1&spm=1001.2101.3001.4242

2.Spring Cloud Config 實現配置中心,看這一篇就夠了:https://www.cnblogs.com/fengzheng/p/11242128.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章