簡介
雖然在開發過程,在本地創建git倉庫操作起來非常方便,但是在實際項目應用中,多個項目組需要通過一個中心服務器來共享配置,所以Spring Cloud配置中心支持遠程git倉庫,以使分散的項目組更方便的進行協作。
基礎環境
- JDK 1.8
- Maven 3.3.9
- IntelliJ 2018.1
- Git
項目源碼
配置遠程git倉庫
首先我在gitee上創建了一個遠程倉庫https://gitee.com/zxuqian/spring-cloud-config-remote
專門用來存放配置文件,然后我們會通過配置文件來訪問此倉庫。然后我們把以前本地的配置文件遷移到此庫中。為了測試效果,我們把web-client.yml
的message
的值修改為:此條消息來自於遠程配置倉庫
配置configserver
現在在我們之前的configserver中作一些配置上的改動。首先為了保留之前的本地倉庫的配置,我們把application.yml
重命名為application-local.yml
。
這個-local
是一個profile
,它的值是-
后面的,即local
,我們可以在bootstrap.yml
中指定使用哪個profile
。比如實際項目中開發階段和生產階段的配置有所不同,所以會有application-development.yml
和application-production.yml
等兩種或以上的配置。
然后新建一個application-remote.yml
文件,添加如下配置內容:
server: port: 8888 spring: cloud: config: server: git: uri: https://gitee.com/zxuqian/spring-cloud-config-remote username: 您的gitee用戶名 password: 您的gitee密碼
因為是自用賬號的倉庫,所以就不提供賬號密碼了,改成自己對應的。這里uri
配置了遠程git倉庫的地址。
最后在bootstrap.yml
中啟用我們的remote
profile:
spring: application: name: config-server profiles: active: remote
spring.profiles.active
即指定了我們的remote
Profile,使用application-remote.yml
配置文件。
測試
使用spring-boot:run
啟動我們的config server,然后訪問http://localhost:8888/web-client/default
,看到如下結果:
{"name":"web-client","profiles":["default"],"label":null,"version":"cbef7d379ef01d68810c3fdc2105b2226ea6c611","state":null,"propertySources":[{"name":"https://gitee.com/zxuqian/spring-cloud-config-remote/web-client.yml","source":{"message":"此條消息來自於遠程配置倉庫","management.endpoints.web.exposure.include":"*"}}]}
message
的值取自於遠程倉庫。這里的web-client/default
是配置文件名/profile
,因為我們的web客戶端項目沒有其他Profile,則默認值為default
,只有這樣寫全,才可以訪問到web-client.yml
的配置。