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/refresh

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM