天天看點

微服務架構 | *2.3 Spring Cloud 啟動及加載配置檔案源碼分析(以 Nacos 為例)

目錄

  • 前言
  • 1. Spring Cloud 什麼時候加載配置檔案
  • 2. 準備 Environment 配置環境
    • 2.1 配置 Environment 環境 SpringApplication.prepareEnvironment()
    • 2.2 使用事件主要器建立并釋出事件 SimpleApplicationEventMulticaster.multicastEvent()
    • 2.3 BootstrapApplicationListener 處理事件,自動導入一些配置類
  • 3. 重新整理應用上下文
    • 3.1 重新整理上下文 SpringApplication.prepareContext()
    • 3.2 初始化上下文的額外操作 SpringApplication.applyInitializers()
    • 3.3 讀取 Nacos 伺服器裡的配置 NacosPropertySourceLocator.locate()
    • 3.4 初始化完成,釋出 ApplicationContextInitializedEvent 事件
    • 3.5 配置加載完成,将監聽器添加進上下文環境
  • 4. 程式運作事件
  • 5. Spring Cloud 啟動及加載配置檔案源碼結構圖小結
  • 最後

參考資料:

《Spring Microservices in Action》

《Spring Cloud Alibaba 微服務原理與實戰》

《B站 尚矽谷 SpringCloud 架構開發教程 周陽》

Spring Cloud 要實作統一配置管理,需要解決兩個問題:如何擷取遠端伺服器配置和如何動态更新配置;在這之前,我們先要知道 Spring Cloud 什麼時候給我們加載配置檔案;

  • 首先,Spring 抽象了一個 Environment 來表示 Spring 應用程式環境配置,整合了各種各樣的外部環境,并且提供統一通路的方法

    getProperty()

  • 在 Spring 應用程式啟動時,會把配置加載到 Environment 中。當建立一個 Bean 時可以從 Environment 中把一些屬性值通過

    @Value

    的形式注入業務代碼;
  • Spring Cloud 是基于 Spring 的發展而來,是以也是在啟動時加載配置檔案,而 Spring Cloud 的啟動程式是主程式類 XxxApplication,我們斷點進入主程式類;
@EnableDiscoveryClient
@SpringBootApplication
public class ProviderApplication {
	public static void main(String[] args) {
	    //【斷點步入】主啟動方法
		SpringApplication.run(ProviderApplication.class, args);
	}
}
           
  • SpringApplication.run()

    運作方法裡會準備 Environment 環境;
public ConfigurableApplicationContext run(String... args) {
        //初始化StopWatch,調用 start 方法開始計時
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        ConfigurableApplicationContext context = null;
        Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
        //設定系統屬性java.awt.headless,這裡為true,表示運作在伺服器端,在沒有顯示器和滑鼠鍵盤的模式下工作,模拟輸入輸出裝置功能
        this.configureHeadlessProperty();
        SpringApplicationRunListeners listeners = this.getRunListeners(args);
        //SpringApplicationRunListeners 監聽器工作--->釋出 ApplicationStartingEvent 事件
        listeners.starting();

        Collection exceptionReporters;
    
    try {
        //持有着 args 參數
        ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
        
        //【斷點步入 2.】準備 Environment 環境--->釋出 ApplicationEnvironmentPreparedEvent 事件
        ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
        this.configureIgnoreBeanInfo(environment);
        //列印 banner
        Banner printedBanner = this.printBanner(environment);
        //建立 SpringBoot 上下文
        context = this.createApplicationContext();
        exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
        
        //【斷點步入 3.】準備應用上下文--->釋出 ApplicationEnvironmentPreparedEvent 事件
        this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
        //重新整理上下文--->釋出 ContextRefreshedEvent 事件
        this.refreshContext(context);
        //在容器完成重新整理後,依次調用注冊的Runners
        this.afterRefresh(context, applicationArguments);
        //停止計時
        stopWatch.stop();
        if (this.logStartupInfo) {
            (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
        }
        //SpringApplicationRunListeners 監聽器工作--->釋出 ApplicationStartedEvent 事件
        listeners.started(context);
        this.callRunners(context, applicationArguments);
    } catch (Throwable var10) {
        this.handleRunFailure(context, var10, exceptionReporters, listeners);
        throw new IllegalStateException(var10);
    }
    
    try {
        //【斷點步入 4.】SpringApplicationRunListeners 監聽程式運作事件--->釋出ApplicationReadyEvent事件
        listeners.running(context);
        return context;
    } catch (Throwable var9) {
        this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);
        throw new IllegalStateException(var9);
    }
}
           
  • 注意,有些同學可能 debug 進不了這裡的 try 語句,可能是因為引入了以下這個依賴,去掉這個依賴即可;
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
    <optional>true</optional>
</dependency>
           

  • 我們進入

    SpringApplication.prepareEnvironment()

    方法裡,該方法主要是根據一些資訊配置 Environment 環境,然後調用 SpringApplicationRunListeners(Spring 應用運作監聽器) 監聽器工作;
private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments) {
    //擷取可配置的環境
    ConfigurableEnvironment environment = this.getOrCreateEnvironment();
    //根據可配置的環境,配置 Environment 環境
    this.configureEnvironment((ConfigurableEnvironment)environment, applicationArguments.getSourceArgs());
    //【斷點步入】告訴監聽者 Environment 環境已經準備完畢
    listeners.environmentPrepared((ConfigurableEnvironment)environment);
    this.bindToSpringApplication((ConfigurableEnvironment)environment);
    if (!this.isCustomEnvironment) {
        environment = (new EnvironmentConverter(this.getClassLoader())).convertEnvironmentIfNecessary((ConfigurableEnvironment)environment, this.deduceEnvironmentClass());
    }
           
  • 進入

    SpringApplicationRunListeners.environmentPrepared()

    方法,該方法的作用是周遊每一個監聽者,并對這些監聽者進行操作;
public void environmentPrepared(ConfigurableEnvironment environment) {
    //使用疊代器周遊監聽者
    Iterator var2 = this.listeners.iterator();
    while(var2.hasNext()) {
        SpringApplicationRunListener listener = (SpringApplicationRunListener)var2.next();
        //【斷點步入】對每一個監聽者進行操作
        listener.environmentPrepared(environment);
    }
}
           

  • EventPublishingRunListener.environmentPrepared()

    方法,發現對每一個監聽者實作的操作是:使用 SimpleApplicationEventMulticaster(事件主要器) 釋出了一個 ApplicationEnvironmentPreparedEvent(應用程式環境準備完成事件);
public void environmentPrepared(ConfigurableEnvironment environment) {
    //【斷點步入】使用事件主要器釋出事件
    this.initialMulticaster.multicastEvent(new ApplicationEnvironmentPreparedEvent(this.application, this.args, environment));
}
           
  • SimpleApplicationEventMulticaster.multicastEvent()

    方法
public void multicastEvent(ApplicationEvent event, @Nullable ResolvableType eventType) {
    //解析出事件類型
    ResolvableType type = eventType != null ? eventType : this.resolveDefaultEventType(event);
    //獲得事件執行者
    Executor executor = this.getTaskExecutor();
    //獲得監聽者疊代器
    Iterator var5 = this.getApplicationListeners(event, type).iterator();

    while(var5.hasNext()) {
        ApplicationListener<?> listener = (ApplicationListener)var5.next();
        //如果有執行者,就通過執行者釋出事件
        if (executor != null) {
            executor.execute(() -> {
                this.invokeListener(listener, event);
            });
        } else {
        //【斷點步入 1.2】沒有執行者就直接發事件
            this.invokeListener(listener, event);
        }
    }
}
           
  • 總結來說就是 Spring Cloud 在配置完 Environment 環境後會釋出一個 ApplicationEnvironmentPreparedEvent(應用程式環境準備完成事件) 告訴所有監聽者,Environment 環境已經配置完畢了;
  • 所有對 ApplicationEnvironmentPreparedEvent 事件感興趣的 Listener 都會監聽這個事件。其中包括 BootstrapApplicationListener;
微服務架構 | *2.3 Spring Cloud 啟動及加載配置檔案源碼分析(以 Nacos 為例)
  • 注意,這裡需要周遊到後面才是 ApplicationEnvironmentPreparedEvent 事件,前面可能是其他事件;

  • 釋出事件後被 BootstrapApplicationListener(Bootstrap 監聽器) 監聽到,調用

    BootstrapApplicationListener.onApplicationEvent()

    方法處理事件:
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
    //擷取目前 Environment 環境
    ConfigurableEnvironment environment = event.getEnvironment();
    //如果環境可用
    if ((Boolean)environment.getProperty("spring.cloud.bootstrap.enabled", Boolean.class, true)) {
        //如果環境來源不包含 bootstrap
        if (!environment.getPropertySources().contains("bootstrap")) {
            ConfigurableApplicationContext context = null;
            String configName = environment.resolvePlaceholders("${spring.cloud.bootstrap.name:bootstrap}");
            Iterator var5 = event.getSpringApplication().getInitializers().iterator();

            while(var5.hasNext()) {
                ApplicationContextInitializer<?> initializer = (ApplicationContextInitializer)var5.next();
                if (initializer instanceof ParentContextApplicationContextInitializer) {
                    context = this.findBootstrapContext((ParentContextApplicationContextInitializer)initializer, configName);
                }
            }

            if (context == null) {
                //【斷點步入】将不是 bootstrap 來源的配置添加進 bootstrap 上下文
                context = this.bootstrapServiceContext(environment, event.getSpringApplication(), configName);
                event.getSpringApplication().addListeners(new ApplicationListener[]{new BootstrapApplicationListener.CloseContextOnFailureApplicationListener(context)});
            }

            this.apply(context, event.getSpringApplication(), environment);
        }
    }
}
           
  • BootstrapApplicationListener.bootstrapServiceContext()

    方法,發現其主要做的是配置自動導入的實作;
private ConfigurableApplicationContext bootstrapServiceContext(ConfigurableEnvironment environment, final SpringApplication application, String configName) {

    //省略其他代碼
    //配置自動裝配的實作
    builder.sources(new Class[]{BootstrapImportSelectorConfiguration.class});
    return context;
}
           
  • 我們搜尋 BootstrapImportSelectorConfiguration(Bootstrap選擇導入配置類) 類,發現其使用 BootstrapImportSelector(Bootstrap導入選擇器) 進行自動配置;
@Configuration
@Import({BootstrapImportSelector.class}) //使用BootstrapImportSelector類進行自動配置
public class BootstrapImportSelectorConfiguration {
    public BootstrapImportSelectorConfiguration() {
    }
}
           
  • BootstrapImportSelector(Bootstrap 導入選擇器) 類的

    selectImports()

    方法使用 Spring 中的 SPI 機制;
public String[] selectImports(AnnotationMetadata annotationMetadata) {
    
    //省略其他代碼
    
    List<String> names = new ArrayList(SpringFactoriesLoader.loadFactoryNames(BootstrapConfiguration.class, classLoader));
}
           
  • 可到 classpath 路徑下查找 META-INF/spring.factories 預定義的一些擴充點,其中 key 為 BootstrapConfiguration;
  • 可以得知給我們導入了一些,其中有兩個配置類 PropertySourceBootstrapConfiguration 和 NacosConfigBootstrapConfiguration(這兩個類在本篇 3.2 和 3.3 裡會提到,用來加載額外配置的);

  • 我們回到

    SpringApplication.run()

    方法裡,在準備完 Environment 環境後,會調用

    SpringApplication.prepareContext()

    方法重新整理應用上下文。我們進入該方法;
private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment, SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {
    //設定上下文的 Environment 環境
    context.setEnvironment(environment);
    this.postProcessApplicationContext(context);
    //【斷點步入 3.2】初始化上下文
    this.applyInitializers(context);
    //【斷點步入 3.4】釋出上下文初始化完畢事件 ApplicationContextInitializedEvent 
    listeners.contextPrepared(context);
    
    //後面代碼省略

    //【斷點步入 3.5】這是該方法的最後一條語句,釋出 
    listeners.contextLoaded(context);
}
           

  • SpringApplication.applyInitializers()

    方法,在應用程式上下文初始化時做一些額外操作;
  • 即執行非 Spring Cloud 官方提供的額外的操作,這裡指 Nacos 自己的操作;
protected void applyInitializers(ConfigurableApplicationContext context) {
    Iterator var2 = this.getInitializers().iterator();

    while(var2.hasNext()) {
        ApplicationContextInitializer initializer = (ApplicationContextInitializer)var2.next();
        Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(initializer.getClass(), ApplicationContextInitializer.class);
        Assert.isInstanceOf(requiredType, context, "Unable to call initializer.");
        //【斷點步入】周遊疊代器,初始化上下文
        initializer.initialize(context);
    }
}
           
  • 這裡的

    .initialize()

    方法最終調用的是 PropertySourceBootstrapConfiguration(Bootstrap 屬性源配置類) ,而這個類就是 1.2 裡準備 Environment 環境時給我們自動導入的。我們進入

    PropertySourceBootstrapConfiguration.initialize()

    方法,得出最後結論:
public void initialize(ConfigurableApplicationContext applicationContext) {

    //省略其他代碼
 
    Iterator var5 = this.propertySourceLocators.iterator();

    while(var5.hasNext()) {
        //PropertySourceLocator 接口的主要作用是實作應用外部化配置可動态加載
        PropertySourceLocator locator = (PropertySourceLocator)var5.next();
        PropertySource<?> source = null;
        //【斷點步入】讀取 Nacos 伺服器裡的配置
        source = locator.locate(environment);
    }
}
           

  • 我們 1.2 裡準備的 Environment 環境中引入的配置類 NacosPropertySourceLocator 實作了該接口,是以最後調用的是

    NacosPropertySourceLocator.locate()

    方法;
  • 該方法将讀取 Nacos 伺服器裡的配置,把結構存到 PropertySource 的執行個體裡傳回;
  • NacosPropertySourceLocator.locate()

    方法源碼如下:
@Override
public PropertySource<?> locate(Environment env) {
    //擷取配置伺服器執行個體,這是Nacos用戶端提供的用于通路實作配置中心基本操作的類
	ConfigService configService = nacosConfigProperties.configServiceInstance();
	if (null == configService) {
		log.warn("no instance of config service found, can't load config from nacos");
		return null;
	}
	long timeout = nacosConfigProperties.getTimeout();
	//Nacos 屬性源生成器
	nacosPropertySourceBuilder = new NacosPropertySourceBuilder(configService, timeout);
	String name = nacosConfigProperties.getName();

    //DataId 字首
	String dataIdPrefix = nacosConfigProperties.getPrefix();
	if (StringUtils.isEmpty(dataIdPrefix)) {
		dataIdPrefix = name;
	}
    //沒有配置 DataId 字首則用 spring.application.name 屬性的值
	if (StringUtils.isEmpty(dataIdPrefix)) {
		dataIdPrefix = env.getProperty("spring.application.name");
	}
    //建立複合屬性源
	CompositePropertySource composite = new CompositePropertySource(NACOS_PROPERTY_SOURCE_NAME);

    //加載共享配置
	loadSharedConfiguration(composite);
	//加載外部配置
	loadExtConfiguration(composite);
	//加載 Nacos 伺服器上應用程式名對應的的配置
	loadApplicationConfiguration(composite, dataIdPrefix, nacosConfigProperties, env);

	return composite;
}
           

  • SpringApplicationRunListeners.contextPrepared()

    釋出事件;
public void contextPrepared(ConfigurableApplicationContext context) {
    //構造疊代器
    Iterator var2 = this.listeners.iterator();
    while(var2.hasNext()) {
        SpringApplicationRunListener listener = (SpringApplicationRunListener)var2.next();
        //【斷點步入】釋出事件
        listener.contextPrepared(context);
    }
}
           
  • EventPublishingRunListener.contextPrepared()

    ,通過 multicastEvent 釋出事件;
public void contextPrepared(ConfigurableApplicationContext context) {
    //釋出 ApplicationContextInitializedEvent 事件
    this.initialMulticaster.multicastEvent(new ApplicationContextInitializedEvent(this.application, this.args, context));
}
           

  • 注意與 3.4 裡的方法不同;
  • SpringApplicationRunListeners.contextLoaded()

    配置加載完成;
public void contextLoaded(ConfigurableApplicationContext context) {
    Iterator var2 = this.listeners.iterator();

    while(var2.hasNext()) {
        SpringApplicationRunListener listener = (SpringApplicationRunListener)var2.next();
        //【斷點步入】
        listener.contextLoaded(context);
    }
}
           
  • EventPublishingRunListener.contextLoaded()

    将監聽器添加進上下文環境;
public void contextLoaded(ConfigurableApplicationContext context) {
    ApplicationListener listener;
    //周遊每一個監聽器(一共有13個,如下圖),将除最後一個監聽器外的監聽器添加進 context 上下文
    for(Iterator var2 = this.application.getListeners().iterator(); var2.hasNext(); context.addApplicationListener(listener)) {
        listener = (ApplicationListener)var2.next();
        if (listener instanceof ApplicationContextAware) {
            //第10個 ParentContextCloseApplicationListener 會進來
            ((ApplicationContextAware)listener).setApplicationContext(context);
        }
    }
    //釋出 ApplicationPreparedEvent 事件
    this.initialMulticaster.multicastEvent(new ApplicationPreparedEvent(this.application, this.args, context));
}
           
微服務架構 | *2.3 Spring Cloud 啟動及加載配置檔案源碼分析(以 Nacos 為例)

  • SpringApplicationRunListeners.running()

    方法,它對每一個監聽器操作;
public void running(ConfigurableApplicationContext context) {
    Iterator var2 = this.listeners.iterator();
    while(var2.hasNext()) {
        SpringApplicationRunListener listener = (SpringApplicationRunListener)var2.next();
        //【斷點步入】操作監聽器,其中就有 EventPublishingRunListener
        listener.running(context);
    }
}
           
  • EventPublishingRunListener.running()

    方法,釋出 ApplicationReadyEvent 事件;
public void running(ConfigurableApplicationContext context) {
    context.publishEvent(new ApplicationReadyEvent(this.application, this.args, context));
}
           

  • SpringApplication.run():加載配置上下文;
    • stopWatch.start():初始化StopWatch,調用 start 方法開始計時;
    • SpringApplicationRunListeners.starting():釋出

      ApplicationStartingEvent

      事件;
    • SpringApplication.prepareEnvironment():準備 Environment 環境;
      • SpringApplicationRunListeners.environmentPrepared():監聽環境準備事件;
        • EventPublishingRunListener.environmentPrepared():對每一個進行操作;
          • SimpleApplicationEventMulticaster.multicastEvent():使用事件主要器釋出

            ApplicationEnvironmentPreparedEvent

          • BootstrapApplicationListener.onApplicationEvent():bootstrap 監聽器處理事件;
            • BootstrapApplicationListener.bootstrapServiceContext():給我們自動導入一些配置類;
    • SpringApplication.printBanner():列印 Banner;
    • printBanner.createApplicationContext():建立 Spring Boot 上下文;
    • SpringApplication.prepareContext():重新整理應用上下文;
      • SpringApplication.applyInitializers():初始化上下文的額外操作;
        • PropertySourceBootstrapConfiguration.initialize():外部化配置;
          • NacosPropertySourceLocator.locate():讀取 Nacos 伺服器裡的配置;
      • SpringApplicationRunListeners.contextPrepared():配置初始化完成;
        • EventPublishingRunListener.contextPrepared():釋出

          ApplicationContextInitializedEvent

      • SpringApplicationRunListeners.contextPrepared():配置加載完成
        • EventPublishingRunListener.contextLoaded():将監聽器添加進上下文環境;
    • StopWatch.stop():停止計時;
    • SpringApplicationRunListeners.started():釋出 ApplicationStartedEvent 事件;
    • SpringApplicationRunListeners.running():監聽程式運作事件;
      • EventPublishingRunListener.running():釋出

        ApplicationReadyEvent

新人制作,如有錯誤,歡迎指出,感激不盡!

歡迎關注公衆号,會分享一些更日常的東西!

如需轉載,請标注出處!

微服務架構 | *2.3 Spring Cloud 啟動及加載配置檔案源碼分析(以 Nacos 為例)

繼續閱讀