spring-cloud-eureka-client功能简要分析

  spring cloud默认使用eureka来做服务治理。作为client的核心功能有两个:服务发现和服务注册。
  通过查看spring-cloud-netflix-eureka-client下的类发现功能核心类是CloudEurekaClient,他继承了netflix的DiscoveryClient。
查看DiscoveryClient源码,注释中写明了DiscoveryClient的四个功能:


image.png

下面一个个来看这些功能是如何实现的。
1.d)服务发现getApplications()

    @Override
    public Applications getApplications() {
        return localRegionApps.get();
    }

localRegionApps是一个成员变量

    private final AtomicReference<Applications> localRegionApps = new AtomicReference<Applications>();

所以一定是有其他地方先set了Applications,getApplications() 方法才能正确返回。通过搜索代码,发现为localRegionApps设值的地方代码基本相似:

EurekaHttpResponse<Applications> httpResponse = clientConfig.getRegistryRefreshSingleVipAddress() == null
                ? eurekaTransport.queryClient.getApplications(remoteRegionsRef.get())
                : eurekaTransport.queryClient.getVip(clientConfig.getRegistryRefreshSingleVipAddress(), remoteRegionsRef.get());
Applications serverApps = httpResponse.getEntity();
localRegionApps.set(this.filterAndShuffle(serverApps));

可以看出localRegionApps的来源,通过eurekaTransport.queryClient获得一个EurekaHttpResponse<Applications>,再进过过滤和乱序处理存入localRegionApps。
  那现在就有两个问题:1.这段代码是由谁执行的,2.eurekaTransport.queryClient是如何工作的。
  通过call Hierarchy发现调用链的最开始:

 class CacheRefreshThread implements Runnable {
        public void run() {
            refreshRegistry();
        }
    }

  查询CacheRefreshThread被使用的地方:

private void initScheduledTasks(){...}

而initScheduledTasks()被调用的地方是DiscoveryClient的构造函数,所以这一切在DiscoveryClient被创建时就开始了。
查看initScheduledTasks()代码:

scheduler.schedule(
                    new TimedSupervisorTask(
                            "cacheRefresh",
                            scheduler,
                            cacheRefreshExecutor,
                            registryFetchIntervalSeconds,
                            TimeUnit.SECONDS,
                            expBackOffBound,
                            new CacheRefreshThread()
                    ),
                    registryFetchIntervalSeconds, TimeUnit.SECONDS);
...
scheduler.schedule(
                    new TimedSupervisorTask(
                            "heartbeat",
                            scheduler,
                            heartbeatExecutor,
                            renewalIntervalInSecs,
                            TimeUnit.SECONDS,
                            expBackOffBound,
                            new HeartbeatThread()
                    ),
                    renewalIntervalInSecs, TimeUnit.SECONDS);

可以看出这是由线程池周期执行的任务,那现在就有两个地方:1.执行的线程池scheduler、cacheRefreshExecutor、cacheRefreshExecutor 2.被执行的回调:HeartbeatThread、CacheRefreshThread。CacheRefreshThread上面知道了是用来设置localRegionApps的,HeartbeatThread从注释来看是用来b)服务续约的:

  /**
     * The heartbeat task that renews the lease in the given intervals.
     */
    private class HeartbeatThread implements Runnable {

        public void run() {
            if (renew()) {
                lastSuccessfulHeartbeatTimestamp = System.currentTimeMillis();
            }
        }
    }

找到三个线程池的初始化代码:

 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()
            );

可以看出eureka默认用了两个线程来做任务调度,两个任务各有一个专属线程独自负责任务的实际执行。这种依靠线程池的隔离策略,在netflix组件中用到的地方有很多。
    找到了CacheRefreshThread是被谁调用的,接着分析eurekaTransport.queryClient是如何工作的。eurekaTransport.queryClient的服务发现方法:getApplications()

@Override
    public EurekaHttpResponse<Applications> getApplications(String... regions) {
        return getApplicationsInternal("apps/", regions);
    }

    private EurekaHttpResponse<Applications> getApplicationsInternal(String urlPath,
            String[] regions) {
        String url = serviceUrl + urlPath;

        if (regions != null && regions.length > 0)
            urlPath = (urlPath.contains("?") ? "&" : "?") + "regions="
                    + StringUtil.join(regions);

        ResponseEntity<EurekaApplications> response = restTemplate.exchange(url,
                HttpMethod.GET, null, EurekaApplications.class);

        return anEurekaHttpResponse(response.getStatusCodeValue(),
                response.getStatusCode().value() == HttpStatus.OK.value()
                        && response.hasBody() ? (Applications) response.getBody() : null)
                                .headers(headersOf(response)).build();
    }

可以看出是向serviceUrl进行http请求获得相关数据的。而serviceUrl是DiscoveryClient在初始化eurekaTransport时传入的。DiscoveryClient初始化时主要有三个参数:ApplicationInfoManager、EurekaClientConfig、ApplicationEventPublisher,通过查看配置类EurekaClientAutoConfiguration可以看到,在SpringCloud中创建的其实是DiscoveryClient的子类CloudEurekaClient:

        @Bean(destroyMethod = "shutdown")
        @ConditionalOnMissingBean(value = EurekaClient.class, search = SearchStrategy.CURRENT)
        public EurekaClient eurekaClient(ApplicationInfoManager manager, EurekaClientConfig config) {
            return new CloudEurekaClient(manager, config, this.optionalArgs,
                    this.context);
        }

ApplicationInfoManager、EurekaClientConfig是自动注入的ApplicationInfoManager manager, EurekaClientConfig config而ApplicationEventPublisher是容器上下文ApplicationContext。继续查找代码可以发现:

        @Bean
        @ConditionalOnMissingBean(value = ApplicationInfoManager.class, search = SearchStrategy.CURRENT)
        public ApplicationInfoManager eurekaApplicationInfoManager(
                EurekaInstanceConfig config) {
            InstanceInfo instanceInfo = new InstanceInfoFactory().create(config);
            return new ApplicationInfoManager(config, instanceInfo);
        }

        @ConfigurationProperties(EurekaClientConfigBean.PREFIX)
        public class EurekaClientConfigBean implements EurekaClientConfig {...}

    ApplicationInfoManager来源于EurekaInstanceConfig ,而EurekaInstanceConfig 其实是由spring创建的EurekaInstanceConfigBean,通过@ConfigurationProperties("eureka.instance")收集了配置文件中的eureka.instance前缀的配置。
    EurekaClientConfig其实是由spring实现并创建的EurekaClientConfigBean,通过@ConfigurationProperties("eureka.client")收集了配置文件中的eureka.client前缀的配置。
    到这可以看出来springcloud做的工作其实就是收集配置并用来初始化DiscoveryClient。其实spring本质上作为一个beanfactory,工作就是创建并管理bean的生命周期。

2.ab)注册和续约
注册方法:register(),查看调用发现在DiscoveryClient的构造函数和renew()函数中被调用了。查看代码:

    /**
     * Register with the eureka service by making the appropriate REST call.
     */
    boolean register() throws Throwable {
        logger.info(PREFIX + "{}: registering service...", appPathIdentifier);
        EurekaHttpResponse<Void> httpResponse;
        try {
            httpResponse = eurekaTransport.registrationClient.register(instanceInfo);
        } catch (Exception e) {
            logger.warn(PREFIX + "{} - registration failed {}", appPathIdentifier, e.getMessage(), e);
            throw e;
        }
        if (logger.isInfoEnabled()) {
            logger.info(PREFIX + "{} - registration status: {}", appPathIdentifier, httpResponse.getStatusCode());
        }
        return httpResponse.getStatusCode() == 204;
    }

其实是通过eurekaTransport.registrationClient.register(instanceInfo)和server进行了一次rest-http调用。instanceInfo是这个客户端本身。
续约方法:renew(),上面说到了续约方法被放入new HeartbeatThread()中,被线程池周期执行。

    /**
     * Renew with the eureka service by making the appropriate REST call
     */
    boolean renew() {
        EurekaHttpResponse<InstanceInfo> httpResponse;
        try {
            httpResponse = eurekaTransport.registrationClient.sendHeartBeat(instanceInfo.getAppName(), instanceInfo.getId(), instanceInfo, null);
            logger.debug(PREFIX + "{} - Heartbeat status: {}", appPathIdentifier, httpResponse.getStatusCode());
            if (httpResponse.getStatusCode() == 404) {
                REREGISTER_COUNTER.increment();
                logger.info(PREFIX + "{} - Re-registering apps/{}", appPathIdentifier, instanceInfo.getAppName());
                long timestamp = instanceInfo.setIsDirtyWithTime();
                boolean success = register();
                if (success) {
                    instanceInfo.unsetIsDirty(timestamp);
                }
                return success;
            }
            return httpResponse.getStatusCode() == 200;
        } catch (Throwable e) {
            logger.error(PREFIX + "{} - was unable to send heartbeat!", appPathIdentifier, e);
            return false;
        }
    }

可以看出也是通过 eurekaTransport.registrationClient进行一次http请求,如果请求失败,则调用一次register()从新注册,如果都失败则返回false。
3.c)注销

@PreDestroy
    @Override
    public synchronized void shutdown() {
        if (isShutdown.compareAndSet(false, true)) {
            logger.info("Shutting down DiscoveryClient ...");

            if (statusChangeListener != null && applicationInfoManager != null) {
                applicationInfoManager.unregisterStatusChangeListener(statusChangeListener.getId());
            }

            cancelScheduledTasks(); //取消上面所说的两个周期任务,并关闭线程池

            // If APPINFO was registered
            if (applicationInfoManager != null
                    && clientConfig.shouldRegisterWithEureka()
                    && clientConfig.shouldUnregisterOnShutdown()) {
                applicationInfoManager.setInstanceStatus(InstanceStatus.DOWN);
                unregister();
            }

            if (eurekaTransport != null) {
                eurekaTransport.shutdown();
            }

            heartbeatStalenessMonitor.shutdown();
            registryStalenessMonitor.shutdown();

            logger.info("Completed shut down of DiscoveryClient");
        }
    }

可以看出主要工作有两部分,1.回收资源 2.调用unregister()通知eureka-server注销。查看unregister()代码:

void unregister() {
        // It can be null if shouldRegisterWithEureka == false
        if(eurekaTransport != null && eurekaTransport.registrationClient != null) {
            try {
                logger.info("Unregistering ...");
                EurekaHttpResponse<Void> httpResponse = eurekaTransport.registrationClient.cancel(instanceInfo.getAppName(), instanceInfo.getId());
                logger.info(PREFIX + "{} - deregister  status: {}", appPathIdentifier, httpResponse.getStatusCode());
            } catch (Exception e) {
                logger.error(PREFIX + "{} - de-registration failed{}", appPathIdentifier, e.getMessage(), e);
            }
        }
    }

可以看出这里也是通过eurekaTransport.registrationClient进行了一次http请求。

综上所述,eureka的主要靠独立的线程池执行周期性任务来执行http请求来进行服务发现的更新和服务续约。而spring所扮演的角色只是DiscoveryClient的创建和管理者,并没有改变eureka的内部功能。我们也可以通过自己创建和管理DiscoveryClient在非springcloud项目中独立地使用eureka,eureka功能完备,自己集成相对简单。总之,就是从server通过http请求获得服务数据而已,可以自己通过浏览器访问:http://localhost:8761/eureka/apps看看数据

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

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,510评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,680评论 6 342
  • 转载请标明出处:http://blog.csdn.net/forezp/article/details/73017...
    方志朋阅读 4,713评论 2 12
  • 我们在学习的过程当中都在思考一问题,初级程序员与高级程序员到底有什么样的差别。我每次很辛苦都完成一个案例,为了一个...
    小子520阅读 450评论 0 0
  • 听说现在你在安睡,突然很安心,睡吧,好好休息才可以正确思考。感赏今天外公外婆也可以安静,感赏今天没什么事发生,投射...
    xueyanL阅读 100评论 0 0