Spring Cloud 覆寫遠端的配置屬性

覆寫遠端的配置屬性

應用的配置源一般都是遠端的Config Server服務器,默認狀況下,本地的配置優先級低於遠端配置倉庫。若是想實現本地應用的系統變量和config文件覆蓋遠端倉庫中的屬性值,能夠經過以下設置:html

spring:
 cloud:
 config:
 allowOverride: true
 overrideNone: true
 overrideSystemProperties: false
複製代碼
  • overrideNone:當allowOverride爲true時,overrideNone設置爲true,外部的配置優先級更低,並且不能覆蓋任何存在的屬性源。默認爲false
  • allowOverride:標識overrideSystemProperties屬性是否啓用。默認爲true,設置爲false意爲禁止用戶的設置
  • overrideSystemProperties:用來標識外部配置是否可以覆蓋系統屬性,默認爲true

客戶端經過如上配置,能夠實現本地配置優先級更高,且不能被覆蓋。因爲咱們基於的Spring Cloud當前版本是Edgware.RELEASE,上面的設置並不能起做用,而是使用了PropertySourceBootstrapProperties中的默認值。具體狀況見issue:https://github.com/spring-cloud/spring-cloud-commons/pull/250,咱們在下面分析時會講到具體的bug源。java

源碼分析

ConfigServicePropertySourceLocator

覆寫遠端的配置屬性歸根結底與客戶端的啓動時獲取配置有關,在獲取到配置以後如何處理?咱們看一下spring cloud config中的資源獲取類ConfigServicePropertySourceLocator的類圖。git

ConfigServicePropertySourceLocator
ConfigServicePropertySourceLocator類圖

ConfigServicePropertySourceLocator實質是一個屬性資源定位器,其主要方法是locate(Environment environment)。首先用當前運行應用的環境的application、profile和label替換configClientProperties中的佔位符並初始化RestTemplate,而後遍歷labels數組直到獲取到有效的配置信息,最後還會根據是否快速失敗進行重試。主要流程以下:github

locate
locate處理流程

locate(Environment environment)調用getRemoteEnvironment(restTemplate, properties, label, state)方法經過http的方式獲取遠程服務器上的配置數據。實現也很簡單,顯示替換請求路徑path中佔位符,而後進行頭部headers組裝,組裝好了就能夠發送請求,最後返回結果。 在上面的實現中,咱們看到獲取到的配置信息存放在CompositePropertySource,那是如何使用它的呢?這邊補充另外一個重要的類是PropertySourceBootstrapConfiguration,它實現了ApplicationContextInitializer接口,該接口會在應用上下文刷新以前refresh()被回調,從而執行初始化操做,應用啓動後的調用棧以下:spring

SpringApplicationBuilder.run() -> SpringApplication.run() -> SpringApplication.createAndRefreshContext() -> SpringApplication.applyInitializers() -> PropertySourceBootstrapConfiguration.initialize()
複製代碼

PropertySourceBootstrapConfiguration

而上述ConfigServicePropertySourceLocator的locate方法會在initialize中被調用,從而保證上下文在刷新以前可以拿到必要的配置信息。具體看一下initialize方法:bootstrap

public class PropertySourceBootstrapConfiguration implements ApplicationContextInitializer<ConfigurableApplicationContext>, Ordered {

	private int order = Ordered.HIGHEST_PRECEDENCE + 10;

	@Autowired(required = false)
	private List<PropertySourceLocator> propertySourceLocators = new ArrayList<>();

	@Override
	public void initialize(ConfigurableApplicationContext applicationContext) {
		CompositePropertySource composite = new CompositePropertySource(
				BOOTSTRAP_PROPERTY_SOURCE_NAME);
		//對propertySourceLocators數組進行排序,根據默認的AnnotationAwareOrderComparator
		AnnotationAwareOrderComparator.sort(this.propertySourceLocators);
		boolean empty = true;
		//獲取運行的環境上下文
		ConfigurableEnvironment environment = applicationContext.getEnvironment();
		for (PropertySourceLocator locator : this.propertySourceLocators) {
			//遍歷this.propertySourceLocators
			PropertySource<?> source = null;
			source = locator.locate(environment);
			if (source == null) {
				continue;
			}
			logger.info("Located property source: " + source);
			//將source添加到PropertySource的鏈表中
			composite.addPropertySource(source);
			empty = false;
		}
		//只有source不爲空的狀況,纔會設置到environment中
		if (!empty) {
			//返回Environment的可變形式,可進行的操做如addFirst、addLast
			MutablePropertySources propertySources = environment.getPropertySources();
			String logConfig = environment.resolvePlaceholders("${logging.config:}");
			LogFile logFile = LogFile.get(environment);
			if (propertySources.contains(BOOTSTRAP_PROPERTY_SOURCE_NAME)) {
				//移除bootstrapProperties
				propertySources.remove(BOOTSTRAP_PROPERTY_SOURCE_NAME);
			}
			//根據config server覆寫的規則,設置propertySources
			insertPropertySources(propertySources, composite);
			reinitializeLoggingSystem(environment, logConfig, logFile);
			setLogLevels(environment);
			//處理多個active profiles的配置信息
			handleIncludedProfiles(environment);
		}
	}
	//...
}
複製代碼

下面咱們看一下,在initialize方法中進行了哪些操做。數組

  • 根據默認的 AnnotationAwareOrderComparator 排序規則對propertySourceLocators數組進行排序
  • 獲取運行的環境上下文ConfigurableEnvironment
  • 遍歷propertySourceLocators時
    • 調用 locate 方法,傳入獲取的上下文environment
    • 將source添加到PropertySource的鏈表中
    • 設置source是否爲空的標識標量empty
  • source不爲空的狀況,纔會設置到environment中
    • 返回Environment的可變形式,可進行的操做如addFirst、addLast
    • 移除propertySources中的bootstrapProperties
    • 根據config server覆寫的規則,設置propertySources
    • 處理多個active profiles的配置信息

初始化方法initialize處理時,先將全部PropertySourceLocator類型的對象的locate方法遍歷,而後將各類方式獲得的屬性值放到CompositePropertySource中,最後調用insertPropertySources(propertySources, composite)方法設置到Environment中。Spring Cloud Context中提供了覆寫遠端屬性的PropertySourceBootstrapProperties,利用該配置類進行判斷屬性源的優先級。bash

private void insertPropertySources(MutablePropertySources propertySources, CompositePropertySource composite) {
		MutablePropertySources incoming = new MutablePropertySources();
		incoming.addFirst(composite);
		PropertySourceBootstrapProperties remoteProperties = new PropertySourceBootstrapProperties();
		new RelaxedDataBinder(remoteProperties, "spring.cloud.config")
				.bind(new PropertySourcesPropertyValues(incoming));
		//若是不容許本地覆寫
		if (!remoteProperties.isAllowOverride() || (!remoteProperties.isOverrideNone()
				&& remoteProperties.isOverrideSystemProperties())) {
			propertySources.addFirst(composite);
			return;
		}
		//overrideNone爲true,外部配置優先級最低
		if (remoteProperties.isOverrideNone()) {
			propertySources.addLast(composite);
			return;
		}
		if (propertySources
				.contains(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)) {
			//根據overrideSystemProperties,設置外部配置的優先級
			if (!remoteProperties.isOverrideSystemProperties()) {
				propertySources.addAfter(
						StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME,
						composite);
			}
			else {
				propertySources.addBefore(
						StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME,
						composite);
			}
		}
		else {
			propertySources.addLast(composite);
		}
	}
複製代碼

上述實現主要是根據PropertySourceBootstrapProperties中的屬性,調整多個配置源的優先級。從其實現能夠看到 PropertySourceBootstrapProperties 對象的是被直接初始化,使用的是默認的屬性值而並未注入咱們在配置文件中設置的。服務器

修復後的實現:微信

@Autowired(required = false)
private PropertySourceBootstrapProperties remotePropertiesForOverriding;
private void insertPropertySources(MutablePropertySources propertySources, CompositePropertySource composite) {
    MutablePropertySources incoming = new MutablePropertySources();
  	incoming.addFirst(composite);
 	PropertySourceBootstrapProperties remoteProperties = remotePropertiesForOverriding == null ? new PropertySourceBootstrapProperties() : remotePropertiesForOverriding;
        ...
    
}
複製代碼

訂閱最新文章,歡迎關注個人公衆號

微信公衆號

參考

Spring Cloud Edgware.RELEASE

相關文章
相關標籤/搜索