本文經過閱讀源碼,分享Spring Cloud Config與@RefreshScope的實現原理。
源碼分析基於Spring Cloud Hoxtongit
閱讀本文以前,最好先了解Environment,PropertySources,可參考 -- SpringBoot源碼解析 -- Logging,Environment啓動web
咱們都知道SpringCloud Config Server啓動後,就能夠經過url訪問,獲取配置內容。
既然這樣,那Config Server中應該就有Controller,對,就是EnvironmentController。spring
EnvironmentController提供的HTTP接口返回的都是Environment,真正的配置內容保存在Environment#PropertySources中。
EnvironmentController經過EnvironmentRepository#findOne獲取對應的Environment。
EnvironmentRepository是一個Environment倉庫,能夠從不一樣的配置中心獲取配置內容,如JDBC、SVN、GIT等等。bootstrap
EnvironmentController中使用的是EnvironmentEncryptorEnvironmentRepository,它會對Environment的內容加解密,EnvironmentEncryptorEnvironmentRepository#delegate是CompositeEnvironmentRepository,很明顯,EnvironmentController的組合類,其中真正的處理類是MultipleJGitEnvironmentRepository,他能夠管理多個git配置中心,實際經過JGitEnvironmentRepository獲取某一個git配置中心上的配置內容。緩存
JGitEnvironmentRepository#findOne -> AbstractScmEnvironmentRepository#findOne微信
public synchronized Environment findOne(String application, String profile, String label, boolean includeOrigin) { NativeEnvironmentRepository delegate = new NativeEnvironmentRepository( getEnvironment(), new NativeEnvironmentProperties()); // #1 Locations locations = getLocations(application, profile, label); delegate.setSearchLocations(locations.getLocations()); // #2 Environment result = delegate.findOne(application, profile, "", includeOrigin); result.setVersion(locations.getVersion()); result.setLabel(label); return this.cleaner.clean(result, getWorkingDirectory().toURI().toString(), getUri()); }
#1
由子類實現,getLocations會拉取配置中心的內容,保存爲本地文件,並返回本地的路徑#2
經過NativeEnvironmentRepository生成Environment併發
JGitEnvironmentRepository#getLocations -> refreshapp
public String refresh(String label) { Git git = null; try { git = createGitClient(); // #1 if (shouldPull(git)) { FetchResult fetchStatus = fetch(git, label); if (this.deleteUntrackedBranches && fetchStatus != null) { deleteUntrackedLocalBranches(fetchStatus.getTrackingRefUpdates(), git); } checkout(git, label); tryMerge(git, label); } ... return git.getRepository().findRef("HEAD").getObjectId().getName(); } ... }
#1
refresh會判斷是否須要fetch,並執行checkout,merge等操做spring-boot
回到AbstractScmEnvironmentRepository#findOne方法#2
步驟,看一下NativeEnvironmentRepository#findOne源碼分析
public Environment findOne(String config, String profile, String label, boolean includeOrigin) { // #1 SpringApplicationBuilder builder = new SpringApplicationBuilder( PropertyPlaceholderAutoConfiguration.class); // #2 ConfigurableEnvironment environment = getEnvironment(profile); builder.environment(environment); // #3 builder.web(WebApplicationType.NONE).bannerMode(Mode.OFF); ... // #4 String[] args = getArgs(config, profile, label); // #5 builder.application() .setListeners(Arrays.asList(new ConfigFileApplicationListener())); // #6 try (ConfigurableApplicationContext context = builder.run(args)) { environment.getPropertySources().remove("profiles"); // #7 return clean(new PassthruEnvironmentRepository(environment).findOne(config, profile, label, includeOrigin)); } ... }
#1
SpringApplicationBuilder使用SpringApplication#run構建一個ApplicationContext#2
構造一個Environment,並賦值給SpringApplication#environment#3
設置SpringApplication的WebApplicationType,定義構造的ApplicationContext的類型#4
設置一些必要的參數,注意:前面保存的本地配置文件的路徑會添加到--spring.config.location參數中,該參數會被下一步驟的ConfigFileApplicationListener使用#5
ConfigFileApplicationListener會經過spring.config.location參數加載本地的配置文件,並添加到Environment#PropertySources中#6
builder.run -> ApplicationContext#run,構造一個ApplicationContext,構造過程當中ConfigFileApplicationListener會完成加載配置文件工做。#7
清理Environment中一些非配置中心的PropertySources。
關於ApplicationContext#run,可參考SpringBoot啓動過程
來看一下其餘應用如何使用Config Server的配置內容。
PropertySourceBootstrapConfiguration實現了ApplicationContextInitializer,
他會讀取bootstrap.properties,bootstrap.yml等配置文件中Config Server的配置信息,並使用PropertySourceLocator獲取Config Server的Environment,最後insertPropertySources將拉取到的PropertySources添加到本應用的Environment中。
ConfigServicePropertySourceLocator#locate方法經過RestTemplate獲取Config Server的Environment,並將結果的PropertySource轉化爲對應的OriginTrackedMapPropertySource。
咱們知道,若是要在運行時動態刷新配置值,須要在Bean上添加@RefreshScope,並使用spring-boot-starter-actuator提供的HTTP接口actuator/refresh來刷新配置值,如今來看看他們的實現原理。
Spring中,bean的範圍有singleton,prototype以及不一樣的scope。
scope有RefreshScope,ThreadScope,SessionScope。
Spring中有@Scope註解和Scope接口以及對應的實現類,而@RefreshScope實際上就是一個scopeName爲refresh的@Scope。
首先,讀取@Scope註解,是在ClassPathBeanDefinitionScanner#doScan方法中,會經過AnnotationScopeMetadataResolver讀取ScopeMetadata信息。
關於這部份內容,可參考 -- @ComponentScan的實現原理
scope的處理是在bean的構造過程當中,AbstractBeanFactory#doGetBean
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType, @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException { ... if (mbd.isSingleton()) { ... else if (mbd.isPrototype()) { ... else { String scopeName = mbd.getScope(); // #1 final Scope scope = this.scopes.get(scopeName); if (scope == null) { throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'"); } try { Object scopedInstance = scope.get(beanName, () -> { beforePrototypeCreation(beanName); try { return createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } }); bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); } ... } ... }
#1
Scope#get方法第二個參數是一個ObjectFactory,負責真正的構造Bean工做。而Scope#get方法主要針對不一樣的Scope作緩存操做。
Scope接口的基礎實如今GenericScope中,而它的子類ThreadScope替換了ScopeCache,使用ThreadLocal保存Bean。另外一個子類RefreshScope則提供了refreshAll等方法。
關於Bean的構造過程,可參考 -- bean構造原理
refresh
引入spring-boot-starter-actuator後,咱們能夠經過actuator/refresh來刷新@RefreshScope標註的類。
處理該請求的是RefreshEndpoint,調用鏈路 RefreshEndpoint#refresh -> ContextRefresher#refresh -> RefreshScope#refreshAll,該方法是以前的
ContextRefresher#refresh會刷新Environment的內容,併發布EnvironmentChangeEvent事件。
RefreshScope#refreshAll會銷燬@RefreshScope標註的bean(還會發布RefreshScopeRefreshedEvent事件),這樣先建立的bean就能夠拿到最新的配置值了。
Spring Boot Actuator中Endpoint相似與SpringMvc的Controller,不過它能夠經過HTTP和JMX暴露服務,之後有時間再說一下這部份內容。
若是您以爲本文不錯,歡迎關注個人微信公衆號,您的關注是我堅持的動力!