項(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依賴呢夜郁?
有了actuator這個依賴什燕,就可以使用/refresh 這個節(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ù)
-
先來訪問/profile 看服務(wù)是否正常運(yùn)行
-
修改git上的application-dev.yml配置
image.png
image.png - 再次訪問/profile
image.png
我們發(fā)現(xiàn)它并沒有發(fā)生變化屎即。這需要我們的一個觸發(fā)操作
發(fā)送一個post
請求給/refresh
image.png
image.png
再來看看 client端 控制臺打印:
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的東西都不能依賴于它們在刷新時被更新,除非它本身在@RefreshScope中(在刷新時它將被重建饺谬,并且它的依賴關(guān)系被重新注入捂刺,在這一點(diǎn)上它們將被 從刷新的@Configuration重新初始化)。