Spring Cloud 為開發人員提供了一系列的工具來快速構建分布式系統的通用模型 。例如:配置管理、服務發現、斷路由、智能路由、微代理、控制總線、一次性Token、全局鎖、決策競選、分布式session、集群狀態等等。分布式系統的協助需要一大堆的模型,使用Spring Cloud開發者能快速的建立支持實現這些模式的服務和應用程序。他們將適用於任何分布式環境,無論是開發者的個人電腦還是生產環境,還是雲平台。
版本:Brixton.SR3
作者:鏈上研發-歐陽
(注:閱讀前置技能樹 Spring 以及Spring的 Property Source、Environment、Profile 和 Spring Boot ,原始文檔有些沒頭沒尾的,適當添加了些內容。)
Spring Cloud中文文檔(持續更新中。。。)
特性
Spring Cloud 專注於提供良好開箱即用的典型方案和可擴展方式。
- 分布式/版本化配置
- 服務注冊/服務發現
- 路由
- 服務間調用
- 負載均衡
- 斷路器
- 全局鎖
- 領導選取和集群狀態監控
- 分布式消息
Cloud Native 應用
Cloud Native是一種持續交付和價值驅動開發推薦的最佳實踐方式。它的理念包含了DevOps、持續交付、微服務、敏捷基礎設施、康威定律,以及根據商業能力對公司進行重組。一個很好的契約例子是12-factor Apps。Spirng Cloud 提供了一系列的工具和特性來促進這些開發,所有的組件都是基於分布式,並且非常容易開始使用。
構建Spring Cloud的大部分特性都是基於Spring Boot的。Spring Cloud的一些特性來源於兩個庫:Spring Cloud Context 和 Spring Cloud Commons。Spring Cloud Context為Spring Cloud應用程序的ApplicationContext提供了基礎的服務(啟動上下文,加密,刷新作用域和環境端點)。Spring Cloud Commons是為實現不同的Spring Cloud實現的抽象。(例如:Spring Cloud Netflix 和 Spring Cloud Consul)
如果使用Sun的JDK遇到Illegal key size
異常,需要安裝JCE
更多信息請查看:
提取文件到JDK/jre/lib/security文件夾(無論你使用的那個版本的JRE/JDK x64/x86)
- 注意:
Spring Cloud是基於非限制性的Apache 2.0 license發布的。如果你發現文檔有問題,或只是想提高它們的質量,請到 github上參與進來。
Spring Cloud 上下文
Spring Boot使用約定的方式來構建Spring應用,例如:它約定了配置文件的位置、通用的端點管理和監控任務。Spring Cloud建立在它的上面,並且增加了一些分布式系統可能需要的組件。
啟動上下文
Spring Cloud會創建一個`Bootstrap Context`,作為Spring應用的`Application Context`的父上下文。初始化的時候,`Bootstrap Context`負責從外部源加載配置屬性並解析配置。這兩個上下文共享一個從外部獲取的`Environment`。`Bootstrap`屬性有高優先級,默認情況下,它們不會被本地配置覆蓋。 `Bootstrap context`和`Application Context`有着不同的約定,所以新增了一個`bootstrap.yml`文件,而不是使用`application.yml` (或者`application.properties`)。保證`Bootstrap Context`和`Application Context`配置的分離。下面是一個例子: **bootstrap.yml**
spring: application: name: foo cloud: config: uri: ${SPRING_CONFIG_URI:http://localhost:8888}
推薦在`bootstrap.yml` or `application.yml`里面配置`spring.application.name`. 你可以通過設置`spring.cloud.bootstrap.enabled=false`來禁用`bootstrap`。
應用上下文層次結構
如果你通過`SpringApplication`或者`SpringApplicationBuilder`創建一個`Application Context`,那么會為spring應用的`Application Context`創建父上下文`Bootstrap Context`。在Spring里有個特性,子上下文會繼承父類的`property sources` and `profiles` ,所以`main application context` 相對於沒有使用Spring Cloud Config,會新增額外的`property sources`。額外的`property sources`有:
- “bootstrap” : 如果在
Bootstrap Context
掃描到PropertySourceLocator
並且有屬性,則會添加到CompositePropertySource。Spirng Cloud Config就是通過這種方式來添加的屬性的,詳細看源碼
ConfigServicePropertySourceLocator`。下面也也有一個例子自定義的例子。 - “applicationConfig: [classpath:bootstrap.yml]” ,(如果有
spring.profiles.active=production
則例如 applicationConfig: [classpath:/bootstrap.yml]#production): 如果你使用bootstrap.yml
來配置Bootstrap Context
,他比application.yml
優先級要低。它將添加到子上下文,作為Spring Boot應用程序的一部分。下文有介紹。
由於優先級規則,Bootstrap Context
不包含從bootstrap.yml
來的數據,但是可以用它作為默認設置。(其實就是最低的優先級,測試過)
你可以很容易的擴展任何你建立的上下文層次,可以使用它提供的接口,或者使用SpringApplicationBuilder
包含的方法(parent()
,child()
,sibling()
)。Bootstrap Context
將是最高級別的父類。擴展的每一個Context
都有有自己的bootstrap property source
(有可能是空的)。擴展的每一個Context
都有不同spring.application.name
。同一層層次的父子上下文原則上也有一有不同的名稱,因此,也會有不同的Config Server配置。子上下文的屬性在相同名字的情況下將覆蓋父上下文的屬性。
注意SpringApplicationBuilder
允許共享Environment
到所有層次,但是不是默認的。因此,同級的兄弟上下文不在和父類共享一些東西的時候不一定有相同的profiles
或者property sources
。
修改Bootstrap屬性配置
源碼位置BootstrapApplicationListener
。
String configName = environment.resolvePlaceholders("${spring.cloud.bootstrap.name:bootstrap}"); String configLocation = environment.resolvePlaceholders("${spring.cloud.bootstrap.location:}"); Map<String, Object> bootstrapMap = new HashMap<>();bootstrapMap.put("spring.config.name",configName); if(StringUtils.hasText(configLocation)){ bootstrapMap.put("spring.config.location", configLocation); }
bootstrap.yml
是由spring.cloud.bootstrap.name
(默認:”bootstrap”)或者spring.cloud.bootstrap.location
(默認空)。這些屬性行為與spring.config.*
類似,通過它的Environment
來配置引導ApplicationContext
。如果有一個激活的profile
(來源於spring.profiles.active
或者Environment
的Api構建),例如bootstrap-development.properties
就是配置了profile
為development
的配置文件.
覆蓋遠程屬性
property sources
被bootstrap context
添加到應用通常通過遠程的方式,比如”Config Server”。默認情況下,本地的配置文件不能覆蓋遠程配置,但是可以通過啟動命令行參數來覆蓋遠程配置。如果需要本地文件覆蓋遠程文件,需要在遠程配置文件里設置授權 spring.cloud.config.allowOverride=true
(這個配置不能在本地被設置)。一旦設置了這個權限,你可以配置更加細粒度的配置來配置覆蓋的方式,
比如:
- spring.cloud.config.overrideNone=true
覆蓋任何本地屬性
- spring.cloud.config.overrideSystemProperties=false
僅僅系統屬性和環境變量
源文件見PropertySourceBootstrapProperties
自定義啟動配置
bootstrap context
是依賴/META-INF/spring.factories
文件里面的org.springframework.cloud.bootstrap.BootstrapConfiguration
條目下面,通過逗號分隔的Spring @Configuration
類來建立的配置。任何main application context
需要的自動注入的Bean可以在這里通過這種方式來獲取。這也是ApplicationContextInitializer
建立@Bean
的方式。可以通過@Order
來更改初始化序列,默認是”last”。
# spring-cloud-context-1.1.1.RELEASE.jar # spring.factories # AutoConfiguration org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration,\ org.springframework.cloud.autoconfigure.RefreshAutoConfiguration,\ org.springframework.cloud.autoconfigure.RefreshEndpointAutoConfiguration,\ org.springframework.cloud.autoconfigure.LifecycleMvcEndpointAutoConfiguration # Application Listeners org.springframework.context.ApplicationListener=\ org.springframework.cloud.bootstrap.BootstrapApplicationListener,\ org.springframework.cloud.context.restart.RestartListener # Bootstrap components org.springframework.cloud.bootstrap.BootstrapConfiguration=\ org.springframework.cloud.bootstrap.config.PropertySourceBootstrapConfiguration,\ org.springframework.cloud.bootstrap.encrypt.EncryptionBootstrapConfiguration,\ org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration,\ org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration
- 警告
小心,你添加的自定義
BootstrapConfiguration
類沒有錯誤的@ComponentScanned
到你的主應用上下文,他們可能是不需要的。使用一個另外的包不被@ComponentScan
或者@SpringBootApplication
注解覆蓋到。
bootstrap context
通過spring.factories
配置的類初始化的所有的Bean都會在SpingApplicatin啟動前加入到它的上下文里去。
自定義引導配置來源:Bootstrap Property Sources
默認的`property source`添加額外的配置是通過配置服務(Config Server),你也可以自定義添加`property source`通過實現`PropertySourceLocator`接口來添加。你可以使用它加配置屬性從不同的服務、數據庫、或者其他。
- 下面是一個自定義的例子:
@Configuration public class CustomPropertySourceLocator implements PropertySourceLocator { @Override public PropertySource<?> locate(Environment environment) { return new MapPropertySource("customProperty", Collections.<String, Object>singletonMap("property.from.sample.custom.source", "worked as intended")); } }
Environment
被ApplicationContext
建立,並傳入property sources
(可能不同個profile
有不同的屬性),所以,你可以從Environment
尋找找一些特別的屬性。比如spring.application.name
,它是默認的Config Server property source
。
如果你建立了一個jar包,里面添加了一個META-INF/spring.factories
文件:
org.springframework.cloud.bootstrap.BootstrapConfiguration=sample.custom.CustomPropertySourceLocator
那么,”customProperty“的PropertySource
將會被包含到應用。
Environment改變
應用程序將監聽EnvironmentChangeEvent
,並且響應這一些改變(添加的ApplicationListeners
可以被用戶用標准的方式增加到@Beans
)。當EnvironmentChangedEvent
觀察到這些值被改變,會觸發這些事情:
- 重新綁定
@ConfigurationProperties
bean到上下文 - 根據
logging.level.*
來舍得屬性的日志級別
默認情況下,Config Client不輪詢Environment
的改變。一般情況,不建議使用這種方式來監測變化(雖然你可以通過@Scheduled
注解來設置)。對於可擴展的應用程序,使用廣播EnvironmentChangeEvent
到所有實例的方式,好過輪詢的方式。(比如使用Spring Cloud Bus項目)。
修改Environment
可以通過發布EnvironmentChangeEvent
來做,這是Spring核心Api的方式。你可以通過觀察/configprops
端點(Spring Boot Actuator的特性)來檢查這些改變綁定到@ConfigurationProperties
的bean的情況。對於DataSource
這樣一個實例,在運行的時候修改maxPoolSize
增加大小,修改的變化不會通知實例里面,可以使用@RefreshScope
來初始化Bean。
@RefreshScope
一個Spring的@Bean
在添加了@RefreshScope
注解,可以解決Bean初始化的時候只能獲得初始配置的問題。比如,在使用DataSource
獲得一個數據庫連接的是時候,當通過Environment
修改數據庫連接字符串的時候,我們可以通過執行@RefreshScope
倆根據修改的配置獲取一個新的URL的連接。
@RefreshScope
的beans,在使用它初始化的時候是延遲代理的。通過RefreshEndpoint
Bean來控制。或者/refresh
請求來重新初始化。
- 注意
@RefreshScope注解在一個
@Configuration
類上面,在重新初始化的時候需要注意到可以相互依賴造成的沖突。
加密和解密
Spring Cloud可以在本地進行預處理的解密,與Config Server有相同的規則,通過設置相同的`encrypt.*`來實現。因此,可以使用加密的值在`{cipher}*`上,在應用通過`Environment`獲得屬值之前進行解密。使用加密特性需要包含Spring Security RSA的包到classpath。Maven依賴”org.springframework.security:spring-security-rsa”。並且,需要在JVM添加JCE擴展。 如果使用Sun的JDK遇到`Illegal key size`異常,需要安裝JCE 更多信息請查看:
提取文件到JDK/jre/lib/security文件夾(無論你使用的那個版本的JRE/JDK x64/x86)。
端點
相對於Spring Boot Actuator的應用,添加了一些管理端點:
- POST to /env 更新
Environment
重新加載@ConfigurationProperties
和日志級別 - /refresh 重新初始化添加了
@RefreshScope
的bean - /restart 重啟初始化ApplicationContext,重啟 (默認是禁用的)
- /pause and /resume 調用ApplicationContext生命周期的方法
stop()
和start()
通用的抽象Spring Cloud Commons
比如服務發現、負載平衡和斷路器等通用的模型,本身是一個抽象層,可以被所有Spring Cloud組件獨立的實現,例如服務發現有具體的實現Eureka、Consul。
Spring RestTemplate作為負載均衡客戶端
RestTemplate
可以使用ribbon自動配置,簡歷一個負載均衡的RestTemplate
使用@Bean
和@LoadBalanced
來預設。
- 警告
RestTemplate
不會通過自動配置建立,必須單獨配置。
@Configuration public class MyConfiguration { @LoadBalanced @Bean RestTemplate restTemplate() { return new RestTemplate(); } } public class MyClass { @Autowired private RestTemplate restTemplate; public String doOtherStuff() { String results = restTemplate.getForObject("http://stores/stores", String.class); return results; } }
這里的URI需要使用虛擬主機名,比如服務名稱,而不是Host名稱。Ribbon客戶端用它來建立一個完整的物理地址。可以查看`RibbonAutoConfiguration`的詳細去設置`RestTemplate`。
多個RestTemplate對象
如果你希望創建一個未負載均衡的`RestTemplate`,可以用正常的方式來注意。訪問負載均衡方式的`RestTemplate`使用`@LoadBalanced`來注解你建立的`@Bean`
@Configuration public class MyConfiguration { @LoadBalanced @Bean RestTemplate loadBalanced() { return new RestTemplate(); } @Primary @Bean RestTemplate restTemplate() { return new RestTemplate(); } } public class MyClass { @Autowired private RestTemplate restTemplate; @Autowired @LoadBalanced private RestTemplate loadBalanced; public String doOtherStuff() { return loadBalanced.getForObject("http://stores/stores", String.class); } public String doStuff() { return restTemplate.getForObject("http://example.com", String.class); } }
- 提示
如果你遇到了
java.lang.IllegalArgumentException: Can not set org.springframework.web.client.RestTemplate field com.my.app.Foo.restTemplate to com.sun.proxy.$Proxy89
的錯誤提示,嘗試使用spring.aop.proxyTargetClass=true
的代理方式注入。
忽略網絡接口
有的時候,對於服務發現注冊,忽略某些命名的網絡接口是非常有用的,比如使用Docker容器的時候。可以通過一些規則設置來忽略這些網絡接口,下面這個配置顯示了忽略“docker0”的入口,所有的入口以“veth.*”來匹配。詳細的配置類見`InetUtilsProperties`。
- application.yml
spring:
cloud:
inetutils:
ignoredInterfaces:
- docker0 - veth.*
Spring Cloud Config
Spring Cloud Config提供了在分布式系統的外部配置的客戶端支持。通過配置服務(Config Server)來為所有的環境和應用提供外部配置的集中管理。這些概念都通過Spring的Environment
和PropertySource
來抽象,所以它可以適用於各類Spring應用,同事支持任何語言的任何應用。它也能為你支持對應用開發環境、測試環境、生產環境的配置、切換、遷移。默認的配置實現通過git實現,同事非常容易的支持其他的擴展(比如svn等)。
快速開始
開始配置服務:
$ git clone https://github.com/spring-cloud/spring-cloud-config.git $ cd spring-cloud-config $ cd spring-cloud-config-server $ ../mvnw spring-boot:run
這是一個 Spring Boot應用,你可以在IDE里面通過ConfigServerApplication
來啟動。
可以看看效果:
$ curl localhost:8888/foo/development {"name":"development","label":"master","propertySources":[ {"name":"https://github.com/scratches/config-repo/foo-development.properties","source":{"bar":"spam"}}, {"name":"https://github.com/scratches/config-repo/foo.properties","source":{"foo":"bar"}} ]}
默認通過git資源加載配置屬性(使用spring.cloud.config.server.git.uri
來配置git地址)。使用這些配置來初始化一個非常輕量的SpringApplication
。這個應用的Environment
加載屬性通過返回JSON對象的請求。
- 這些請求的Http資源下面這些
/{application}/{profile}[/{label}] /{application}-{profile}.yml /{label}/{application}-{profile}.yml /{application}-{profile}.properties /{label}/{application}-{profile}.properties
- application 根據
spring.config.name
來獲得 - profile 激活的剖面,比如
spring.profiles.active = test
- label git資源的label 默認是master
必須提供一個git資源,Spring Cloud Config Server才能從遠程git服務pull資源來配置,例如:
spring:
cloud:
config:
server: git: uri: https://github.com/spring-cloud-samples/config-repo
客戶端用法
配置服務一般作為單獨的服務部署,各個需要的應用會添加一個客戶來從配置服務獲取配置。而配置服務的配置,依賴git提交的配置文件。
在Spring Boot應用里面,使用這個特性需要添加spring-cloud-config-client
的依賴。比較方便是方式是添加一個Spring Boot的starter依賴org.springframework.cloud:spring-cloud-starter-config
。對於Maven用戶,有一個spring-cloud-starter-parent的父pom文件。對於Gradle和Spring CLI用戶,可以用Spring IO版本管理文件。下面是Maven配置:
- pom.xml
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.5.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Brixton.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <!-- 上面版本可能依賴一些snapshots版本,添加spring的資源 --> <repositories> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>http://repo.spring.io/milestone</url> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories>
創建一個簡單是Spring Boot的web應用:
@SpringBootApplication @RestController public class Application { @RequestMapping("/") public String home() { return "Hello World!"; } public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
當你運行的時候,這個應用默認啟動8080端口,默認它會尋找本地的8888端口的配置服務。你可以修改bootstrap.properties
文件配置服務的uri:
spring.cloud.config.uri: http://myconfigserver.com
啟動加載的屬性可以通過/env
來查看,它有很高的優先級:
$ curl localhost:8080/env { "profiles":[], "configService:https://github.com/spring-cloud-samples/config-repo/bar.properties":{"foo":"bar"}, "servletContextInitParams":{}, "systemProperties":{...}, ... }
一條屬性是"configService:https://github.com/spring-cloud-samples/config-repo/bar.properties":{"foo":"bar"}
里面的配置,它有最高優先級的。屬性源中的 URL是git倉庫的地址而不是配置服務器的URL。
配置服務服務端 Spring Cloud Config Server
Spring Cloud Config Server提供了一個基本Http的,資源API的,可擴展的配置(使用key-value的properties或者相似的yaml的方式)。通過添加@EnableConfigServer
非常容易的嵌入到了Spring Boot應用里面。下面是一個配置服務的app:
- ConfigServer.java
@SpringBootApplication @EnableConfigServer public class ConfigServer { public static void main(String[] args) { SpringApplication.run(ConfigServer.class, args); } }
Spring Boot應用通常默認啟動8080端口,Config Server通常切換到8888端口。在Config Server 的jar文件里面configserver.yml默認配置了spring.config.name=configserver
,你可以在自己的配置文件里面修改。
- application.properties
server.port: 8888 spring.cloud.config.server.git.uri: file://${user.home}/config-repo
${user.home}/config-repo
是一個git資源包含YAML文件和屬性文件。
在Windows系統里面,如果文件URL是絕對路徑,前面有驅動符號,你需要多增加個’/’符號, file:///${user.home}/config-repo.
- 下面是在創建例如上面的Git倉庫配方
$ cd $HOME $ mkdir config-repo $ cd config-repo $ git init . $ echo info.foo: bar > application.properties $ git add -A . $ git commit -m "Add application.properties"
使用本地的git資源最好只用作測試使用,生產環境建議使用git服務器。
初始化配置的是非常高效快速的,當你使用特別大的二進制文件,可能會遇到第一個請求延遲的情況或者服務內存溢出的情況。
- 補充
配置默認存儲在tmp文件目錄, linux系統默認會清理一定時間沒有更新的tmp目錄下的文件。生產環境上演出這一出悲劇。
資源庫環境Environment Repository
Config Server的配置數據存儲在哪里?
解決這個問題的是`EnvironmentRepository`,服務`Environment`對象。`Environment`對象是對Spring的Environment(其中包括 propertySources做為主要屬性)的淺拷貝。Environment資源被參數化成了3個變量:
- {application} 對應客戶端的”spring.application.name”
- {profile} 對應客戶端的”spring.profiles.active”(逗號分隔)
- {label} 服務端依賴的資源文件標記(比如git 的master)
配置庫資源實現的表形式與Spring Boot的配置相關,比如{application}參數來自”spring.config.name”,{profiles}來自”spring.profiles.active”,profiles的優先級規則也和Spring Boot應用一樣。激活的profiles的優先級高於默認的,有多個profiles,最后一個起作用。與Map的set操作類似。
例如:
- bootstrap.yml
spring:
application: name: foo profiles: active: dev,mysql
與Spring Boot應用程序一樣,這些參數也可以通過環境變量或命令行參數進行設置。
如果配置庫是基於文件的,服務器將優先根據foo.yml,在根據application.yml創建一個Environment對象。如果這些 YAML文件中有指定了Spring profiles,那么這些profiles將有較高優先級,同時如果存在指定profile后綴YAML(或properties)文件,這些文件就比默認的文件具有更高的優先級。高優先級的配置優先轉成Environment對象中的PropertySource。(這和單獨的Spring Boot系統使用的規則是一樣的)
后端的git
EnvironmentRepository
默認情況下,通過依賴git服務來實現。git可以非常方便的修改升級配置,而且可以審查變更記錄。可以在你的配置服務(比如application.yml
文件)里面添加spring.cloud.config.server.git.uri
配置指定git資源。你也可以直接使用file:
前綴來配置一個本地資源,來快速開始你的服務。為了提高配置服務的高可用性和擴展性,你需要有指向同一個版本庫服務器的所有實例,所以只有一個共享文件系統是可行的。即使在這種情況下,最好是使用ssh:
協議共享文件系統存儲庫,以便服務器可以克隆它,並使用本地工作副本作為高速緩存。
這個資源的實現通過映射HTTP資源的{label}參數為git label(提交id,分支名稱或tag)。如果git分支或tag的名稱包含一個斜杠 (“/”),HTTP URL中的label需要使用特殊字符串”(_)”來替代(為了避免與URL的其他的參數路徑混淆)。如果使用了命令行客戶端如 curl,請謹慎處理URL中的括號(例如:在shell下請使用引號”來轉義他們)。
Git URI占位符
Spring Cloud配置服務支持git資源的url使用 {application}
、 {profile}
和 {label}
占位符。這的label指的是git的label。所以,你可以很容易的為每一個應用配置資源:
spring:
cloud:
config:
server: git: uri: https://github.com/myorg/{application}
或者,每一個資源一個{profile}
的策略。
模式匹配和多個資源庫
它還支持更復雜的規則使用application
,profile
來做模式匹配。這個模式的格式,試音逗號分隔的 {application}/{profile}
列表作為通配符。
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
如果{application}/{profile}
沒有匹配到任何參數,它將默認使用的spring.cloud.config.server.git.uri
定義的uri。在上面的例子中,simple
資源匹配simple/*
(匹配應用名字為simple
的所有profile
)。local
資源匹配應用名稱為local/*
的所有的profile
。
注意,在上述”simple”的例子中,只使用一行來設置屬性的便捷方式, 如果你需要設置其他屬性(如credentials, pattern, etc.),你需要使用完整的格式才能表示清楚。
在配置里面的pattern
屬性實際上是一個數組,你可以使用YAML
數組(屬性文件里面使用[0]、[1])來綁定多個參數。你可能需要使用它,如果你用多個profiles來運行應用。
spring:
cloud:
config:
server:
git:
uri: https://github.com/spring-cloud-samples/config-repo
repos:
development:
pattern:
- */development - */staging uri: https://github.com/development/config-repo staging: pattern: - */qa - */production uri: https://github.com/staging/config-repo
如果你的模式匹配參數不是以*
結尾,又沒有包含profile,Spring Cloud會推測匹配所有的profiles,比如*/staging
是["*/staging", "*/staging,*"]
的簡化寫法。通常,在本地開發環境運行development
的profile,在遠程環境運行cloud
的profile。
每個資源也可以選擇在子目錄存儲配置文件,通過關鍵字searchPaths
來查詢定義的目錄。例如:
spring:
cloud:
config:
server: git: uri: https://github.com/spring-cloud-samples/config-repo searchPaths: foo,bar*
在這個例子里面,服務會從foo/目錄和以bar開頭的目錄查詢配置文件。
默認情況下,當第一次請求的時候,服務clone遠程資源。你也可以配置在啟動的時候clone。
spring:
cloud:
config:
server:
git:
uri: https://git/common/config-repo.git repos: team-a: pattern: team-a-* cloneOnStart: true uri: http://git/team-a/config-repo.git team-b: pattern: team-b-* cloneOnStart: false uri: http://git/team-b/config-repo.git team-c: pattern: team-c-* uri: http://git/team-a/config-repo.git
在這個例子里面,服務啟動的時候會clone team-a
的配置,它是在接受到請求之前就進行的。其它資源則在資源第一次請求的時候clone。
遠程配置的基礎身份認證通過添加username
和password
屬性,例如:
spring:
cloud:
config:
server: git: uri: https://github.com/spring-cloud-samples/config-repo username: trolley password: strongpassword
如果你沒有使用https和用戶認證,也可以便捷的使用SSH,只需要將keys存儲在默認的目錄(~/.ssh),uri指向SSH地址(git@github.com:configuration/cloud-configuration)。服務使用JGit來訪問你需要的任何配置文件。可以在~/.git/config
下配置https代理,也可以使用JVM系統屬性-Dhttps.proxyHost
和-Dhttps.proxyPort
來配置。
如果你清楚你的~/.git
目錄,你可以使用git config --global
來配置。比如:git config --global http.sslVerify false
。
查詢占位符
Spring Cloud配置服務也支持查詢路徑使用 {application}
和{profile}
(如果需要{label}
)占位符。比如:
spring:
cloud:
config:
server: git: uri: https://github.com/spring-cloud-samples/config-repo searchPaths: '{application}'
在與application
相同名字的路徑中查找配置庫中的文件。在這里,通配符同樣有效。
版本控制系統后端文件的使用
后面發現已經有翻譯版本了:附上
- Spring Cloud Config
- http://www.xyuu.cn/spring-cloud-config-zhcn.html
- Spring Cloud Netflix
- http://www.xyuu.cn/spring-cloud-netflix-zhcn.html