SpringCloud Config配置中心原理以及環(huán)境切換方式
Config配置中心原理以及環(huán)境切換
springCloud config項目,用來為分布式的微服務系統(tǒng)中提供集成式外部配置支持,分為客戶端和服務端
spring官方如下介紹:
Spring Cloud Config provides server and client-side support for externalized configuration in a distributed system. With the Config Server you have a central place to manage external properties for applications across all environments. The concepts on both client and server map identically to the Spring Environment and PropertySource abstractions, so they fit very well with Spring applications, but can be used with any application running in any language. As an application moves through the deployment pipeline from dev to test and into production you can manage the configuration between those environments and be certain that applications have everything they need to run when they migrate. The default implementation of the server storage backend uses git so it easily supports labelled versions of configuration environments, as well as being accessible to a wide range of tooling for managing the content. It is easy to add alternative implementations and plug them in with Spring configuration.
簡而言之: 通過配置服務(Config Server)來為所有的環(huán)境和應用提供外部配置的集中管理,這些概念都通過spring的Environment和PropertySource來抽象,所以他可以適用于各類Spring應用,它也能對應用的開發(fā)環(huán)境、測試環(huán)境、生成環(huán)境的配置做切換、遷移
原理介紹

git服務器會從遠程git拉取配置文件,并存入到本地git文件庫,當遠程git不可用時,會從本地git文件庫拉取配置信息
一、Config Server 引入依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>接入配置中心,讓客戶端可以發(fā)現(xiàn)服務端,啟動類加上@EnableConfigServer,@EnableDiscoveryClient注解,命名chu-config
配置中心服務器,會根據(jù)spring.cloud.config.server.git.uri來找到配置數(shù)據(jù)(它可以是git存儲庫的位置,也可以是本地文件),這是必須的,Config server才能從遠程Git服務pull資源來配置在遠程碼云倉儲中新建application.yml和chu-user.yml配置文件
二、Config client
在項目中,基本上所有的基礎微服務都是config client,它們都通過config server做外部配置集中管理和動態(tài)環(huán)境切換
客戶端默認拉取規(guī)則如下:
/{name}-{profile}.yml
/{label}-{name}-{profile}.ymlname:即spring.application.nameprofile: 激活的剖面label: git分支,默認是master
例如,這里搭建一個chu-user服務:
引入客戶端依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-client</artifactId>
</dependency>在配置文件中通過spring.cloud.config.discovery.enabled=true和spring.cloud.config.discovery.service-id=chu-config來注冊發(fā)現(xiàn)配置中心服務端
測試:
上頭我們介紹了配置中心的拉取規(guī)則
遠程碼云chu-user.yml上有個test:123的屬性,在chu-user服務上可通過@Value("${test}")注解獲取到,如果chu-user服務上的配置文件中也有個test:456的屬性,默認情況下,Config Server優(yōu)先
經(jīng)過測試,我們證明了config client可以成功的拉取到遠程服務器的配置文件,那么不同環(huán)境的配置切換拉取怎么做呢?
1.在遠程碼云上改造chu-user.yml配置文件如下:
--- spring: profiles: dev isDev: true --- spring: profiles: pro isDev: false
重啟config server,在瀏覽器輸入localhost:8888/chu-user-dev.yml可以成功拉取到配置信息
2.客戶端通過spring.cloud.config.profile=pro/dev來指定拉取的環(huán)境配置
測試:啟動config server和config client,并在chu-user服務控制臺看到

分別拉取到application#pro環(huán)境和chu-user#pro環(huán)境信息,同時程序通過@Value("${isDev}")讀取配置值為false
每個資源也可以選擇在子目錄存儲配置文件,通過關(guān)鍵字searchPaths來查詢定義的目錄,例如
spring:
cloud:
config:
server:
git:
uri: https://gitee.com/China_shenzhen_git/one-config-server
search-paths: /config,'{application}'將會從config目錄和與application相同名字的目錄中開始查詢配置文件
Config server如果希望客戶端能夠授權(quán)訪問配置中心庫,可以引入security配置,引入依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
security:
basic:
enabled: true
user:
name: config-repo
password: 123456那么客戶端就需要增加spring.cloud.config.username=config-repo ,password=123456配置來授權(quán)訪問配置中心服務器
注意
spring profiles進行不同環(huán)境版本配置分離、切換,通過spring.profiles.active=dev,mysql,如果配置文件基于文件的,服務器將優(yōu)先根據(jù){applicationName}.yml,在根據(jù)application.yml創(chuàng)建一個Environment對象,如果這些yml文件中有了指定的spring profiles,那么這些profiles將有較高優(yōu)先級spring.profile.avtive是指定spring boot運行的環(huán)境,而spring.cloud.config.profile是客戶端指定拉取資源庫的profile配置,如果有多個profiles,最后一個起作用
簡易配置中心原理及流程說明
以下將詳細說明簡易配置中心原理及流程說明。
原理
在啟動后優(yōu)先于spring默認配置掃描器增加所需配置項,spring將讀取第一個值使之生效。
源碼詳解
對spring有了解的朋友都知道,spring對于默認組件或一些配置都是寫在META-INF文件夾下的spring.factories文件中,spring默認配置項也是配置在此。
在spring-boot-1.5.9.RELEASE.jar!/META-INF/spring.factories文件中,有一項與配置相關(guān)的配置
# Application Listeners 監(jiān)聽 org.springframework.context.ApplicationListener=\ org.springframework.boot.context.config.ConfigFileApplicationListener # Environment Post Processors 環(huán)境處理 org.springframework.boot.env.EnvironmentPostProcessor=\ org.springframework.boot.cloud.CloudFoundryVcapEnvironmentPostProcessor,\ org.springframework.boot.env.SpringApplicationJsonEnvironmentPostProcessor
此監(jiān)聽類為配置文件關(guān)鍵類。
public class ConfigFileApplicationListener implements EnvironmentPostProcessor, SmartApplicationListener, Ordered {}可以看到,此監(jiān)聽實現(xiàn)了EnvironmentPostProcessor,SmartApplicationListener與Ordered。
// 監(jiān)聽回調(diào)函數(shù)
@Override
public void onApplicationEvent(ApplicationEvent event) {
?? ?if (event instanceof ApplicationEnvironmentPreparedEvent) {
?? ? ? ?//在此初始化配置項
?? ??? ?onApplicationEnvironmentPreparedEvent(
?? ??? ??? ??? ?(ApplicationEnvironmentPreparedEvent) event);
?? ?}
?? ?if (event instanceof ApplicationPreparedEvent) {
?? ??? ?onApplicationPreparedEvent(event);
?? ?}
}
//配置文件初始化讀取
private void onApplicationEnvironmentPreparedEvent(
?? ?ApplicationEnvironmentPreparedEvent event) {
?? ?//加載所有EnvironmentPostProcessor類型bean,此時掃描還未開始,獲取到的都必須是上面說的spring.factories中配置的Environment Post Processors。
?? ?List<EnvironmentPostProcessor> postProcessors = loadPostProcessors();
?? ?//增加自己
?? ?postProcessors.add(this);
?? ?//排序
?? ?AnnotationAwareOrderComparator.sort(postProcessors);
?? ?for (EnvironmentPostProcessor postProcessor : postProcessors) {
?? ? ? ?//執(zhí)行
?? ??? ?postProcessor.postProcessEnvironment(event.getEnvironment(),
?? ??? ??? ??? ?event.getSpringApplication());
?? ?}
}
//加載application.yml及指定profile文件
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment,
?? ??? ?SpringApplication application) {
?? ??? ?//加載
?? ?addPropertySources(environment, application.getResourceLoader());
?? ?configureIgnoreBeanInfo(environment);
?? ?bindToSpringApplication(environment, application);
}配置中心思路
加載流程及優(yōu)先級清楚了,那么可以開始動手了~
由于執(zhí)行到這步的時候,還未開始掃描,所以使用注解是無效的。那么新建一個/META-INF/spring.factories文件,并增加相應配置,在ConfigFileApplicationListener之前執(zhí)行即可。
簡易搭建例子
老規(guī)矩,不會寫詳細的步驟,更希望大家能明白原理,舉一反三喲
以修改tomcat端口為例子,由于時間關(guān)系,只在代碼中模擬獲得配置項。
新建配置類PropertiesConfigPostProcessor
public class PropertiesConfigPostProcessor implements EnvironmentPostProcessor, Ordered {
? ? //優(yōu)先于ConfigFileApplicationListener
? ? public static final int DEFAULT_ORDER = Ordered.HIGHEST_PRECEDENCE + 9;
? ? @Override
? ? public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
? ? ? ?//此時PropertySources中無application配置項,我們新增一個server.port為8999的配置。此步驟如為真實配置中心則可自行獲得。
? ? ? ? environment.getPropertySources().addLast(new MapPropertySource("configServerInitProperties", new QuickHashMap<String, Object>().quickPut("server.port", 8999)));
? ? }
? ? @Override
? ? public int getOrder() {
? ? ? ? return DEFAULT_ORDER;
? ? }
}新建一個/META-INF/spring.factories文件,內(nèi)容為
org.springframework.boot.env.EnvironmentPostProcessor=\ top.wboost.example.PropertiesConfigPostProcessor
-application.yml配置
server: ? port: 8000
啟動后,日志顯示端口為8999.
我們查看系統(tǒng)中存在的配置項為如下所示(省略其他配置項)
{
? ? "data": {
? ? ? ? "applicationConfigurationProperties": {
? ? ? ? ? ? "server.port,class org.springframework.boot.context.config.ConfigFileApplicationListener$ConfigurationPropertySources": 8000
? ? ? ? },
? ? ? ? "configServerInitProperties,class org.springframework.core.env.MapPropertySource": {
? ? ? ? ? ? "server.port": 8999
? ? ? ? }
? ? },
? ? "info": {
? ? ? ? "code": 10906,
? ? ? ? "message": "執(zhí)行成功",
? ? ? ? "systemCode": "DO_OK"
? ? },
? ? "status": 0
}以上就是簡易流程,懂得原理,可自行擴展!希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java并發(fā)編程之CountDownLatch源碼解析
這篇文章主要介紹了Java并發(fā)編程之CountDownLatch源碼解析,文中有非常詳細的代碼示例,對正在學習java并發(fā)編程的小伙伴們有很好的幫助,需要的朋友可以參考下2021-04-04
JavaWeb?Listener?利用Session統(tǒng)計在線人數(shù)
這篇文章主要為大家介紹了JavaWeb?Listener?利用Session統(tǒng)計在線人數(shù),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09
Java語言實現(xiàn)簡單FTP軟件 FTP軟件本地窗口實現(xiàn)(5)
這篇文章主要為大家詳細介紹了Java語言實現(xiàn)簡單FTP軟件,F(xiàn)TP軟件本地窗口的實現(xiàn)方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-03-03
Java throw Exception實現(xiàn)異常轉(zhuǎn)換
這篇文章主要介紹了Java throw Exception實現(xiàn)異常轉(zhuǎn)換,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-04-04
Spring Cloud-Feign服務調(diào)用的問題及處理方法
Feign 是一個聲明式的 REST 客戶端,它用了基于接口的注解方式,很方便實現(xiàn)客戶端配置。接下來通過本文給大家介紹Spring Cloud-Feign服務調(diào)用,需要的朋友可以參考下2021-10-10
Springboot?Mybatis使用pageHelper如何實現(xiàn)分頁查詢
這篇文章主要介紹了Springboot?Mybatis使用pageHelper如何實現(xiàn)分頁查詢問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05

