前面寫過一篇《Spring Cloud Bus 實現配置實時更新》,是使用配置中心管理配置,使用spring cloud bus來實現實時通知。對于簡單的SpringBoot應用,其實不需要使用配置中心也可以實現動態刷新配置。
參考:http://www.ythuaji.com.cn/article/215175.html
文章使用springboot版本:2.0.4.RELEASE springcloud版本Finchley.SR1
1. 依賴
需要引入下面三個依賴:
1
2
3
|
compile( 'org.springframework.cloud:spring-cloud-starter-config' ) compile( 'org.springframework.boot:spring-boot-starter-actuator' ) compile( 'org.springframework.boot:spring-boot-starter-web' ) |
(1)spring-cloud-starter-config是為了實現刷新配置
(2)spring-boot-starter-actuator是為了暴露修改/刷新配置的接口
(3)spring-boot-starter-web是為了可以訪問暴露的修改/刷新配置的接口
2. 配置暴露接口
application.properties
1
2
3
4
|
#使用端口 9999 server.port= 9999 #暴露接口 management.endpoints.web.exposure.include=env,refresh |
(1)env接口,可以獲取配置(GET),也可以修改配置(POST)
(2)refresh接口,可以刷新配置(POST),使得@RefreshScope標注的value可以重新注入。
3. @RefreshScope
在需要實時刷新配置的地方加上@RefreshScope注解
4. 啟動服務
5. 修改配置
訪問localhost:9999/actuator/env(GET),可以獲得此時的配置
訪問localhost:9999/actuator/env(POST)
1
2
3
4
|
{ "name" : "somekey" , "value" : "newvalue" } |
如上可以把配置中somekey對應的值改為newvalue
6. 獲取配置值
不調用刷新接口,直接獲取注入的配置值,發現還是舊的值
7. 刷新配置 重新獲取
訪問localhost:9999/actuator/refresh(POST)刷新配置
重新獲取注入的配置值,發現是新的值
總結
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注服務器之家的更多內容!
原文鏈接:https://blog.csdn.net/lblblblblzdx/article/details/81784237