SpringCloud Config自動刷新配置源碼分析

1、配置中心

先來一張流程圖:
服務器

Spring Cloud Bus 如何觸發 Refresh?
注:配置中內心我是配置的mq發送消息this

  1. RefreshBusEndpoint中加了@Endpoint(
    id = "bus-refresh"
    )註解,他就會監控這個/actuator/bus-refresh這個路徑code

  2. 而後調用到了busRefresh方法,發佈了RefreshRemoteApplicationEvent事件。blog

  3. 這個事件發佈過程當中會使用到ApplicationListenerMethodAdapter來處理,部分代碼以下:事件

protected Object doInvoke(Object... args) {
		Object bean = getTargetBean();
		ReflectionUtils.makeAccessible(this.method);
		try {
		//反射執行的方法是BusAutoConfiguration#acceptLocal()
			return this.method.invoke(bean, args);
		}
  1. 反射執行方法會發送mq消息,而後由各個配置中心客戶端接收,接受方法爲BusAutoConfiguration#acceptRemote
  2. 這個方法會發布RefreshRemoteApplicationEvent事件
  3. 這個事件由RefreshListener負責接收,而後去處理刷新配置
public void onApplicationEvent(RefreshRemoteApplicationEvent event) {
        Set<String> keys = this.contextRefresher.refresh();
        log.info("Received remote refresh request. Keys refreshed " + keys);
    }
  1. 監聽觸發後,調用到ContextRefresher的refresh()方法
public synchronized Set<String> refresh() {
		Set<String> keys = refreshEnvironment();
		////對應的bean刷新
		this.scope.refreshAll();
		return keys;
	}
  1. 先看 refreshEnvironment()方法
public synchronized Set<String> refreshEnvironment() {
    //獲取以前的配置
		Map<String, Object> before = extract(
				this.context.getEnvironment().getPropertySources());
		//從新建立一個SpringApplication並獲取新的配置
		addConfigFilesToEnvironment();
		//比較配置不一樣的key
		Set<String> keys = changes(before,
				extract(this.context.getEnvironment().getPropertySources())).keySet();
		//發佈配置改變事件
		this.context.publishEvent(new EnvironmentChangeEvent(context, keys));
		return keys;
	}
  1. EnvironmentChangeEvent事件由ConfigurationPropertiesRebinder監聽,監聽到以後會調用rebind方法
@ManagedOperation
	public void rebind() {
		this.errors.clear();
		for (String name : this.beans.getBeanNames()) {
		    //初始化bean
			rebind(name);
		}
	}
  1. 再點到this.scope.refreshAll()方法
public void refreshAll() {
        //銷燬bean
		super.destroy();
		this.context.publishEvent(new RefreshScopeRefreshedEvent());
	}
  1. RefreshScopeRefreshedEvent事件由EurekaClientConfigurationRefresher監聽,進行對eureka服務器重連的操做。
相關文章
相關標籤/搜索