spring cloud --eureka簡單分析
阿新 • • 發佈:2018-12-12
大家知道,將一個普通的springboot 應用註冊到Eureka Server只需要兩步
- 在應用主類新增@EnableDiscoveryClient註解
- 在application.properties中配置eureka.client.serviceUrl.defaultZone
順著這條思路,首先看下@EnableDiscoveryClient有什麼類容
/** * Annotation to enable a DiscoveryClient implementation. * @author Spencer Gibb */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @Import(EnableDiscoveryClientImportSelector.class) public @interface EnableDiscoveryClient { /** * If true, the ServiceRegistry will automatically register the local server. */ boolean autoRegister() default true; }
從註釋就能知道,該註解主要是開啟DiscoveryClient的例項。梳理關係後可得到下圖
其中,左邊的org.springframework.cloud.client.discovery.DiscoveryClient是spring cloud的介面,定義了用來發現服務的常用抽象方法。org.springframework.cloud.netflix.eureka.EurekaDiscoveryClient是對介面的實現,從命名就可以知道,是對Eureka的發現服務的封裝,所以依賴了com.netflix.discovery.EurekaClient介面,EurekaClient又繼承於LookupService,主要是定義了發現服務的抽象方法,而真正去實現發現服務功能的類是com.netflix.discovery.DiscoveryClient。
要看一個類,首先就看類頭部定義的註釋
/** * The class that is instrumental for interactions with <tt>Eureka Server</tt>. * * <p> * <tt>Eureka Client</tt> is responsible for a) <em>Registering</em> the * instance with <tt>Eureka Server</tt> b) <em>Renewal</em>of the lease with * <tt>Eureka Server</tt> c) <em>Cancellation</em> of the lease from * <tt>Eureka Server</tt> during shutdown * <p> * d) <em>Querying</em> the list of services/instances registered with * <tt>Eureka Server</tt> * <p> * * <p> * <tt>Eureka Client</tt> needs a configured list of <tt>Eureka Server</tt> * {@link java.net.URL}s to talk to.These {@link java.net.URL}s are typically amazon elastic eips * which do not change. All of the functions defined above fail-over to other * {@link java.net.URL}s specified in the list in the case of failure. * </p> * * @author Karthik Ranganathan, Greg Kim * @author Spencer Gibb * */ @Singleton
這個類用於Eureka Server相互協作;
Eureka Client主要負責下面的任務:
- 向Eureka Server註冊服務例項
- 向Eureka Server獲取服務租約
- 在服務關閉時,向Eureka Server取消租約
- 查詢Eureka Server中的服務例項列表
Eureka Client還要配置Eureka Server的URL列表 -----------------------------------------------------------------------------------------------------------------------------