EurekaServer自動裝配及啟動流程解析


在開始本篇文章之前,我想你對SpringCloud和SpringBoot的基本使用已經比較熟悉了,如果不熟悉的話可以參考我之前寫過的文章
本篇文章的源碼基於SpringBoot2.0,SpringCloud的Finchley.RELEASE

@EnableEurekaServer注解

我們知道,在使用Eureka作為注冊中心的時候,我們會在啟動類中增加一個@EnableEurekaServer注解,這個注解我們是一個自定義的EnableXXX系列的注解,主要作用我們之前也多次提到了,就是引入配置類而已。看一下源碼吧

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({EurekaServerMarkerConfiguration.class})
public @interface EnableEurekaServer {
}

引入了一個配置類EurekaServerMarkerConfiguration,看一下這個類的具體內容

@Configuration
public class EurekaServerMarkerConfiguration {

	@Bean
	public Marker eurekaServerMarkerBean() {
		return new Marker();
	}

	class Marker {
	}
}

現在看這里好像難以理解,這是啥意思,搞個空的類干啥的,不要着急,接着往下看

自動裝配

既然注解上沒有找到我們想要的東西,那么就看一下spring.factories文件吧,這里自動配置的實現類是EurekaServerAutoConfiguration

由於這個類涉及的代碼實在是太多了,這里就不貼了,咱們直接來解析這個類:

1. 引入EurekaServerInitializerConfiguration類

看名字就知道了這個類是負責Eureka的初始化工作的,這個類實現了SmartLifecycle接口,所以在spring初始化和銷毀的時候,就會分別調用它的start和stop方法

首先看一下start方法

public void start() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					//啟動EurekaServer
eurekaServerBootstrap.contextInitialized(EurekaServerInitializerConfiguration.this.servletContext);
					log.info("Started Eureka Server");

					publish(new EurekaRegistryAvailableEvent(getEurekaServerConfig()));
					EurekaServerInitializerConfiguration.this.running = true;
					publish(new EurekaServerStartedEvent(getEurekaServerConfig()));
				}
				catch (Exception ex) {
					// Help!
					log.error("Could not initialize Eureka servlet context", ex);
				}
			}
		}).start();
	}

這個代碼好像比較直接了當啊,直接就起個線程啟動了EurekaServer,然后發布了一些啟動事件,來看啟動的過程吧


public void contextInitialized(ServletContext context) {
                try {
            //初始化執行環境
                        initEurekaEnvironment();
            //初始化上下文
                        initEurekaServerContext();

                        context.setAttribute(EurekaServerContext.class.getName(), this.serverContext);
                }
                catch (Throwable e) {
                        log.error("Cannot bootstrap eureka server :", e);
                        throw new RuntimeException("Cannot bootstrap eureka server :", e);
                }
        }

這里一共包含初始化環境和初始化上下文兩個分支

初始化執行環境

這個不是很重要,可以過濾掉


protected void initEurekaEnvironment() throws Exception {
                log.info("Setting the eureka configuration..");
               //AWS相關的東西,可以忽略
                String dataCenter = ConfigurationManager.getConfigInstance()
                                .getString(EUREKA_DATACENTER);
                if (dataCenter == null) {
                        log.info(
                                        "Eureka data center value eureka.datacenter is not set, defaulting to default");
                        ConfigurationManager.getConfigInstance()
                                        .setProperty(ARCHAIUS_DEPLOYMENT_DATACENTER, DEFAULT);
                }
                else {
                        ConfigurationManager.getConfigInstance()
                                        .setProperty(ARCHAIUS_DEPLOYMENT_DATACENTER, dataCenter);
                }
        //設置 Eureka 環境,默認為test
                String environment = ConfigurationManager.getConfigInstance()
                                .getString(EUREKA_ENVIRONMENT);
                if (environment == null) {
                        ConfigurationManager.getConfigInstance()
                                        .setProperty(ARCHAIUS_DEPLOYMENT_ENVIRONMENT, TEST);
                        log.info(
                                        "Eureka environment value eureka.environment is not set, defaulting to test");
                }
                else {
                        ConfigurationManager.getConfigInstance()
                                        .setProperty(ARCHAIUS_DEPLOYMENT_ENVIRONMENT, environment);
                }
        }
初始化上下文

protected void initEurekaServerContext() throws Exception {
                // 設置json與xml序列化工具
                JsonXStream.getInstance().registerConverter(new V1AwareInstanceInfoConverter(),
                                XStream.PRIORITY_VERY_HIGH);
                XmlXStream.getInstance().registerConverter(new V1AwareInstanceInfoConverter(),
                                XStream.PRIORITY_VERY_HIGH);

                if (isAws(this.applicationInfoManager.getInfo())) {
                        this.awsBinder = new AwsBinderDelegate(this.eurekaServerConfig,
                                        this.eurekaClientConfig, this.registry, this.applicationInfoManager);
                        this.awsBinder.start();
                }

                EurekaServerContextHolder.initialize(this.serverContext);

                log.info("Initialized server context");

                // 同步Eureka集群數據
                int registryCount = this.registry.syncUp();
                this.registry.openForTraffic(this.applicationInfoManager, registryCount);

                // 注冊監控統計信息
                EurekaMonitors.registerAllStats();
        }

這個方法中同步集群數據和注冊監控信息都涉及的內容比較多,所以本篇文章就不再展開了,請關注我留意后續文章

@ConditionalOnBean({Marker.class})

看到這里就揭開了開篇@EnableEurekaServer注解注入的那個bean的含義了。也就是說如果咱們的啟動類沒有使用@EnableEurekaServer注解的話,這個自動配置類就不會執行,那也就沒有Eureka的事了

@EnableConfigurationProperties({EurekaDashboardProperties.class, InstanceRegistryProperties.class})

深入這個注解發現這個還是使用的@Import注解的機制引入了兩個類,這個注解在之前的源碼解析文章中也多次提到了,這里就不展開了

EurekaDashboardProperties這個類比較簡單,主要是Eureka的控制台的相關配置

//控制台默認路徑
private String path = "/";
//是否開啟控制台
private boolean enabled = true;

InstanceRegistryProperties,這個類是控制Eureka的注冊時的配置信息

    //每分鍾續約次數
    @Value("${eureka.server.expectedNumberOfRenewsPerMin:1}") 
	private int expectedNumberOfRenewsPerMin = 1;
    //默認打開的通信數量
	@Value("${eureka.server.defaultOpenForTrafficCount:1}")
	private int defaultOpenForTrafficCount = 1;
@PropertySource("classpath:/eureka/server.properties")

相信大家比較熟悉這個注解,加載Eureka的配置文件而已

配置文件中也僅僅只包含這個信息

spring.http.encoding.force=false
自動注入的bean

EurekaServerAutoConfiguration類上幾個注解就解析完了,接着看一下這個類中注入的幾個比較重要的類吧

配置類EurekaServerConfigBeanConfiguration

EurekaServerConfig
如果當前應用允許注冊到其他Eureka服務中時,也就是屬性eureka.client.fetch-registry為true時。就設置屬性registrySyncRetries的值為5,這個屬性的意思是當Eureka服務器啟動時嘗試去獲取集群里其他服務器上的注冊信息的次數

EurekaController

這個就是Eureka自己的controller了,控制台的相關信息就是從這里獲取的

ServerCodecs

設置Eureka的序列化工具

PeerAwareInstanceRegistry

集群注冊信息同步相關的類,請期待后續深入解析文章

FilterRegistrationBean

EurekaServer接受請求的一個攔截器,感興趣的同學可以研究一下


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM