在跟我學Spring Cloud(Finchley版)-19-配置中心-Spring Cloud Config 一節中,已實現使用Git倉庫作爲Config Server的後端存儲,本節詳細探討如何配置Git倉庫。
一、佔位符支持
Config Server的佔位符支持{application}、{profile}和{label}。
示例:
server:
port: 8080
spring:
application:
name: microservice-config-server
cloud:
config:
server:
git:
uri: https://git.oschina.net/itmuch/{application}
username:
password:
使用這種方式,即可輕鬆支持一個應用對應一個Git倉庫。同理,也可支持一個profile對應一個Git倉庫。
二、模式匹配
模式匹配指的是帶有通配符的{application}/{profile}名稱的列表。如果{application}/{profile}不匹配任何模式,它將會使用spring.cloud.config.server.git.uri
定義的URI。
spring:
cloud:
config:
server:
git:
uri: https://github.com/spring-cloud-samples/config-repo
repos:
simple: https://github.com/simple/config-repo
special:
pattern: special*/dev*,*special*/dev*
uri: https://github.com/special/config-repo
local:
pattern: local*
uri: file:/home/configsvc/config-repo
該例中,對於simple倉庫,它只匹配所有配置文件中名爲simple的應用程序,它的模式等同於simple/*
。local倉庫則匹配所有配置文件中以local開頭的所有應用程序的名稱。
三、搜索目錄
很多場景下,我們可能把配置文件放在了Git倉庫子目錄中,此時可以使用search-paths指定,search-path同樣支持佔位符。
spring:
cloud:
config:
server:
git:
uri: http://git.oschina.net/itmuch/spring-cloud-config-repo
search-paths: foo,bar*
這樣,Config Server就會在Git倉庫根目錄、foo子目錄、以及所有以bar開始的子目錄中查找配置文件。
四、啓動時加載配置文件
默認情況下,在配置被首次請求時,Config Server纔會clone Git倉庫。我們也可讓Config Server在啓動時就clone Git倉庫,例如。
spring:
cloud:
config:
server:
git:
uri: https://github.com/spring-cloud-samples/config-repo
repos:
team-a:
pattern: microservice-*
clone-on-start: true
uri: http://git.oschina.net/itmuch/spring-cloud-config-repo
將屬性spring.cloud.config.server.git.repos.*.clone-on-start
設爲true,即可讓Config Server啓動時clone指定Git倉庫。
當然,也可使用spring.cloud.config.server.git.clone-on-start = true
進行全局配置。
配置clone-on-start = true,可幫助Config Server啓動時快速識別錯誤的配置源(例如無效的Git倉庫)。
小技巧
將以下包的日誌級別設爲DEBUG,即可打印Config Server請求Git倉庫的細節。我們可藉助日誌,更好地理解Config Server的Git倉庫配置,同時,也便於我們快速定位問題。
logging:
level:
org.springframework.cloud: DEBUG
org.springframework.boot: DEBUG
本文首發
http://www.itmuch.com/spring-cloud/finchley-20/