spring cloud eureka client

本文是在搭建好eureka服务的基础上,来进行分析的。还有姊妹篇eureka server。

eureka Client工作的过程

大体工作过程,分为以下几个阶段,如下图所示:


eureka Client工作

DiscoveryClient初步了解

服务在读取配置信息,有一个特殊的客户端接口org.springframework.cloud.client.discovery.DiscoveryClient,可以通过注入这个接口来获取一些客户端配置。

@RestController
public class ServiceInstanceRestController {
    @Autowired
    private DiscoveryClient discoveryClient;

     /**
     * 填入任一EurekaClient的实例名,便可获取该服务的相关信息
     *
     * @param applicationName EurekaClient的appName对应spring.application.name属性
     * @return
     */
    @RequestMapping("service-instances/{applicationName}")
    public List<ServiceInstance> serviceInstancesByApplication(@PathVariable String applicationName) {
        return discoveryClient.getInstances(applicationName);
    }

    /**
     * 获取当前服务的描述
     *
     * @return
     */
    @RequestMapping("description")
    public String description() {
        return discoveryClient.description();
    }

    /**
     * 获取所有的服务名
     *
     * @return
     */
    @RequestMapping("getServices")
    public List<String> getServices() {
        return discoveryClient.getServices();
    }
}

源码和配置

我们都知道Eureka是netfix的杰作,在了解了上述的spring的DiscoveryClient后,我们来看看com.netflix.discovery.DiscoveryClient.java这个类,他也是Eureka Client的核心聚焦类。

client主要类图.png

该类封装了注册、心跳等一系列行为。所以,下面的代码分析,我们从注册和心跳开始。
EurekaClientConfig.java中,该类封装了Client与Server交互的配置信息。其中有两个比较重要的属性:
fetchRegistry为true表示该Client从Server中拉取注册信息,对应的配置为eureka.client.fetch-registry
registerWithEureka为true表示该Client是否注册到Server上,对应的配置为eureka.client. register-with-eureka
这两个值会用在DiscoveryClient中,若都为false,表示既不服务发现,也不服务注册。

在下面会定义一个调度线程池,大小为2,一个是用于心跳,一个用于缓存刷新。

            scheduler = Executors.newScheduledThreadPool(2,
                    new ThreadFactoryBuilder()
                            .setNameFormat("DiscoveryClient-%d")
                            .setDaemon(true)
                            .build());

            heartbeatExecutor = new ThreadPoolExecutor(
                    1, clientConfig.getHeartbeatExecutorThreadPoolSize(), 0, TimeUnit.SECONDS,
                    new SynchronousQueue<Runnable>(),
                    new ThreadFactoryBuilder()
                            .setNameFormat("DiscoveryClient-HeartbeatExecutor-%d")
                            .setDaemon(true)
                            .build()
            );  // use direct handoff

            cacheRefreshExecutor = new ThreadPoolExecutor(
                    1, clientConfig.getCacheRefreshExecutorThreadPoolSize(), 0, TimeUnit.SECONDS,
                    new SynchronousQueue<Runnable>(),
                    new ThreadFactoryBuilder()
                            .setNameFormat("DiscoveryClient-CacheRefreshExecutor-%d")
                            .setDaemon(true)
                            .build()
            );  // use direct handoff

全量拉取注册表

下面为DicoveryClient#getAndStoreFullRegistry方法

private void getAndStoreFullRegistry() throws Throwable {
       //获取当前版本
        long currentUpdateGeneration = fetchRegistryGeneration.get();
        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 (apps == null) {
            logger.error("The application is null for some reason. Not storing this information");
        } else if (fetchRegistryGeneration.compareAndSet(currentUpdateGeneration, currentUpdateGeneration + 1)) {
            //版本比较,重新过滤和洗牌apps,并将UP状态的Application放入本地区域apps中
            localRegionApps.set(this.filterAndShuffle(apps));
            logger.debug("Got full registry with apps hashcode {}", apps.getAppsHashCode());
        } else {
            logger.warn("Not updating applications as another thread is updating it already");
        }
    }

其中,从eureka拉取所有Application信息的请求是{{eureka-server}}/eureka/apps。
因为该方法可以同时被多个线程访问,是线程不安全的(会产生各种覆盖现象)。所以其中的关键值 localRegionApps为本地区域应用,采用AtomicReference<Applications>类型;fetchRegistryGeneration为当前client存储的注册表版本,类型为AtomicLong。这两个值都是使用原子类型来确保其安全。具体使用,参见上面源码。
该方法的输出结果(样例,便于后面方法的了解):

<applications>
    <versions__delta>1</versions__delta>
    <apps__hashcode>UP_5_</apps__hashcode>
    <application>
        <name>ADMIN-CLIENT</name>
        <instance>
            <instanceId>admin-client2</instanceId>
            <hostName>localhost</hostName>
            <app>ADMIN-CLIENT</app>
            <ipAddr>192.168.1.105</ipAddr>
            <status>UP</status>
            <overriddenstatus>UNKNOWN</overriddenstatus>
            <port enabled="true">8082</port>
            <securePort enabled="false">443</securePort>
            <countryId>1</countryId>
            <dataCenterInfo class="com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo">
                <name>MyOwn</name>
            </dataCenterInfo>
            <leaseInfo>
                <renewalIntervalInSecs>30</renewalIntervalInSecs>
                <durationInSecs>90</durationInSecs>
                <registrationTimestamp>1546006066759</registrationTimestamp>
                <lastRenewalTimestamp>1546006066759</lastRenewalTimestamp>
                <evictionTimestamp>0</evictionTimestamp>
                <serviceUpTimestamp>1546006066759</serviceUpTimestamp>
            </leaseInfo>
            <metadata>
                <management.port>8082</management.port>
                <jmx.port>63368</jmx.port>
            </metadata>
            <homePageUrl>http://localhost:8082/</homePageUrl>
            <statusPageUrl>http://localhost:8082/actuator/info</statusPageUrl>
            <healthCheckUrl>http://localhost:8082/actuator/health</healthCheckUrl>
            <vipAddress>admin-client</vipAddress>
            <secureVipAddress>admin-client</secureVipAddress>
            <isCoordinatingDiscoveryServer>false</isCoordinatingDiscoveryServer>
            <lastUpdatedTimestamp>1546006066759</lastUpdatedTimestamp>
            <lastDirtyTimestamp>1546006040724</lastDirtyTimestamp>
            <actionType>ADDED</actionType>
        </instance>
        <instance>
            <instanceId>admin-client1</instanceId>
            ...
        </instance>
    </application>
    <application>
        <name>EUREKA-SERVICE</name>
        <instance>
           ...
        </instance>
        <instance>
            ...
        </instance>
    </application>
    <application>
        <name>ADMIN-SERVER</name>
        <instance>
           ...
        </instance>
    </application>
</applications>

Tips:Eureka Instance的运行状态有5种:

  • UP:存活,
  • DOWN :不再发送心跳的,
  • STARTING : 启动中,
  • OUT_OF_SERVICE :关闭了的,
  • UNKNOWN :未知服务。

增量拉取注册表

下面为DicoveryClient#getAndUpdateDelta方法

private void getAndUpdateDelta(Applications applications) throws Throwable {
        long currentUpdateGeneration = fetchRegistryGeneration.get();

        Applications delta = null;
        EurekaHttpResponse<Applications> httpResponse = eurekaTransport.queryClient.getDelta(remoteRegionsRef.get());
        if (httpResponse.getStatusCode() == Status.OK.getStatusCode()) {
            delta = httpResponse.getEntity();
        }

        if (delta == null) {
            ......
        } else if (fetchRegistryGeneration.compareAndSet(currentUpdateGeneration, currentUpdateGeneration + 1)) {
            String reconcileHashCode = "";
            //使用重入锁机制来更新增量注册信息
            if (fetchRegistryUpdateLock.tryLock()) {
                try {
                //更新本地缓存
                    updateDelta(delta);
                //计算一致性hashCode
                    reconcileHashCode = getReconcileHashCode(applications);
                } finally {
                    fetchRegistryUpdateLock.unlock();
                }
            } else {
                logger.warn("Cannot acquire update lock, aborting getAndUpdateDelta");
            }
            if (!reconcileHashCode.equals(delta.getAppsHashCode()) || clientConfig.shouldLogDeltaDiff()) {
               //比较版本,CAS更新。发起远程调用线程
                reconcileAndLogDifference(delta, reconcileHashCode);  
            }
        } else {
            logger.warn("Not updating application delta as another thread is updating it already");
            logger.debug("Ignoring delta update with apps hashcode {}, as another thread is updating it already", delta.getAppsHashCode());
        }
    }

其中,从eureka server拉取增量Application信息的请求是{{eureka-server}}/eureka/apps/delta。
本段代码使用重入锁机制来确保多线程操作,防止数据污染。
其一致性hashCode举例为:UP_3_形式的。

服务注册

在拉取完注册表后,client会注册自己到server中去。DiscoveryClient#register方法。

boolean register() throws Throwable {
        EurekaHttpResponse<Void> httpResponse;
        try {
            httpResponse = eurekaTransport.registrationClient.register(instanceInfo);
        } catch (Exception e) {
            logger.warn(PREFIX + "{} - registration failed {}", appPathIdentifier, e.getMessage(), e);
            throw e;
        }
        return httpResponse.getStatusCode() == 204;
    }

其中,注册client到server的请求是{{eureka-server}}/eureka/apps/{{client-instant-appName}}
响应码为204表示成功。

服务续约(心跳)

boolean renew() {
        EurekaHttpResponse<InstanceInfo> httpResponse;
        try {
            httpResponse = eurekaTransport.registrationClient.sendHeartBeat(instanceInfo.getAppName(), instanceInfo.getId(), instanceInfo, null);
            if (httpResponse.getStatusCode() == Status.NOT_FOUND.getStatusCode()) {
                REREGISTER_COUNTER.increment();
                long timestamp = instanceInfo.setIsDirtyWithTime();
                boolean success = register();
                if (success) {
                    instanceInfo.unsetIsDirty(timestamp);
                }
                return success;
            }
            return httpResponse.getStatusCode() == Status.OK.getStatusCode();
        } catch (Throwable e) {
            logger.error(PREFIX + "{} - was unable to send heartbeat!", appPathIdentifier, e);
            return false;
        }
    }

其中,从client续约到server的请求是{{eureka-server}}/eureka/apps/{{client-instance-appName}}/{client-instance-id}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,295评论 6 512
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,928评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,682评论 0 357
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,209评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,237评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,965评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,586评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,487评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,016评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,136评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,271评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,948评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,619评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,139评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,252评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,598评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,267评论 2 358

推荐阅读更多精彩内容