電子商務平臺源碼請加企鵝求求:一零三八七七四六二六。 在 SpringCloud 的衆多組件中,Eureka 功能的重要性不言而喻,也許斷路器能夠不須要,配置中心也能夠不須要,服務網關也能夠不須要, 但 Eureka 不可或缺。因此,重點在於 Eureka。java
本文的關注點bash
Client 功能:app
能夠註冊到 EurekaServer負載均衡
能夠從 EurekaServer 獲取列表dom
能夠根據實例列表中負載均衡調用服務ide
咱們在使用 Client 的時候,須要使用 @EnableDiscoveryClient 表示本身是一個 Client ,也就是說,這個註解必定有很大的做用,咱們經過追蹤該註解,會看到註解上的註釋:fetch
Annotation to enable a DiscoveryClient implementation.ui
能夠知道,這個註解和 DiscoveryClient 綁定了。this
進入這個類查看。該類果真有一個 register 方法。關鍵代碼以下:spa
/**
* Register with the eureka service by making the appropriate REST call.
*/
boolean register() throws Throwable {
EurekaHttpResponse<Void> httpResponse = eurekaTransport.registrationClient.register(instanceInfo);
return httpResponse.getStatusCode() == 204;
}
複製代碼
註釋說道:經過適當的REST調用來註冊eureka服務。
這個 registrationClient 有不少實現,默認的實現是 SessionedEurekaHttpClient。當返回 204 的時候,表示註冊成功。
同時,這個register方法也是維持心跳的方法。經過定時任務默認 30 秒調用一次。
一樣,在 DiscoveryClient 類中,咱們發現有一個 getApplications 方法,該方法代碼以下:
@Override
public Applications getApplications() {
return localRegionApps.get();
}
複製代碼
而這個 localRegionApps 從哪裏獲取數據呢?咱們使用 IDEA 發現該變量有幾個地方能夠 set 數據,其中關鍵方法 getAndStoreFullRegistry, 該方法被 2 個地方使用 :一個是更新,一個是從註冊中心獲取,該方法主要邏輯爲:
private void getAndStoreFullRegistry() throws Throwable {
Applications apps = null;
EurekaHttpResponse<Applications> httpResponse = clientConfig.getRegistryRefreshSingleVipAddress() == null
? eurekaTransport.queryClient.getApplications(remoteRegionsRef.get())
: eurekaTransport.queryClient.getVip(clientConfig.getRegistryRefreshSingleVipAddress(), remoteRegionsRef.get());
if (httpResponse.getStatusCode() == Status.OK.getStatusCode()) {
apps = httpResponse.getEntity();
}
if (fetchRegistryGeneration.compareAndSet(currentUpdateGeneration, currentUpdateGeneration + 1)) {
localRegionApps.set(this.filterAndShuffle(apps));
}
}
複製代碼
使用 HTTP 請求從EurekaServer 獲取數據,其中最重要的數據就是 Applications,而後,使用 CAS 更新版本,將數據進行打亂(防止使用相同的實例接受啓動過程當中的流量),最後放進 Applications 中。
同時,使用 CacheRefreshThread 每 30 秒(默認)更新一次。
當咱們調用一個被 @FeignClient 註解標識的遠程方法時,和普通的 RPC 同樣,SpringCloud 也是使用的 JDK 的動態代理,這個動態代理的的攔截類則是 HystrixInvocationHandler, 核心方法 invoke 代碼以下:
HystrixInvocationHandler.this.dispatch.get(method).invoke(args);
SpringCloud 經過 Future 的 get 方法阻塞等待結果。能夠看到,SpringCloud 默認是有斷路器的。是否開啓根據 feign.hystrix.enable 屬性決定是否開啓。 這行代碼最後調用的是 SynchronousMethodHandler 的 invoke 方法,代碼以下:
public Object invoke(Object[] argv) throws Throwable {
RequestTemplate template = buildTemplateFromArgs.create(argv);
Retryer retryer = this.retryer.clone();
while (true) {
try {
return executeAndDecode(template);
} catch (RetryableException e) {
retryer.continueOrPropagate(e);
if (logLevel != Logger.Level.NONE) {
logger.logRetry(metadata.configKey(), logLevel);
}
continue;
}
}
}
複製代碼
該方法會進行重試——若是重試失敗的話。能夠看得出來, executeAndDecode 方法就是真正的 RPC 調用。
那麼,SpringCloud 是如何進行負載均衡選擇對應的實例的呢?
在上面的executeAndDecode 方法中,會調用 LoadBalancerFeignClient 的 execute 方法。最終會調用 ZoneAwareLoadBalancer 負載均衡器的 chooseServer 方法, 該方法內部代理了一個 IRule 類型的的負載均衡策略。而默認的策略則是輪詢,看看這個 choose 方法的實現:
/**
* Get a server by calling {@link AbstractServerPredicate#chooseRandomlyAfterFiltering(java.util.List, Object)}.
* The performance for this method is O(n) where n is number of servers to be filtered.
*/
@Override
public Server choose(Object key) {
ILoadBalancer lb = getLoadBalancer();
Optional<Server> server = getPredicate().chooseRoundRobinAfterFiltering(lb.getAllServers(), key);
if (server.isPresent()) {
return server.get();
} else {
return null;
}
}
/**
* Choose a server in a round robin fashion after the predicate filters a given list of servers and load balancer key.
*/
public Optional<Server> chooseRoundRobinAfterFiltering(List<Server> servers, Object loadBalancerKey) {
List<Server> eligible = getEligibleServers(servers, loadBalancerKey);
if (eligible.size() == 0) {
return Optional.absent();
}
return Optional.of(eligible.get(nextIndex.getAndIncrement() % eligible.size()));
}
複製代碼
上面的兩個方法就是 SpringCloud 負載均衡的策略了,從代碼中能夠看到,他使用了一個 nextIndex 變量取餘實例的數量,獲得一個 Service。
在 AbstractLoadBalancerAwareClient 的 executeWithLoadBalancer 方法中獲得輪詢到的 Server 後,執行 FeignLoadBalancer的 executer 方法。
最後,使用 feign 包下的 Client接口的默認實現類 Default 執行 convertResponse方法,使用 Java BIO 進行請求並返回數據。
經過今天的代碼分析,咱們知道了幾點:
Client 如何註冊,當啓動的時候,會調用 DiscoveryClient 的register方法進行註冊,同時,還有一個 30 秒間隔的定時任務也可能(小心跳返回 404)會調用這個方法,用於服務心跳。
Client 如何獲取服務列表,Client 也是經過 DiscoveryClient 的getAndStoreFullRegistry方法對服務列表進行獲取或者更新。
Client 如何負載均衡調用服務,Client 經過使用 JDK 的動態代理,使用 HystrixInvocationHandler 進行攔截。而其中的負載均衡策略實現不一樣,默認是經過一個原子變量遞增取餘機器數,也就是輪詢策略, 而這個類就是 ZoneAwareLoadBalancer。
固然,因爲 SpringCloud 代碼是在不少,本文也沒有作到逐行剖析,可是,咱們已經瞭解了他的主要代碼在什麼地方以及設計,這對於咱們理解 SpringCloud 以及排查問題是有幫助的。