SpringCloud源码阅读2-Eureka客户端的秘密(中)

简介: SpringCloud源码阅读2-Eureka客户端的秘密(中)

2.1.2 fetchRegistry

private boolean fetchRegistry(boolean forceFullRegistryFetch) {
        Stopwatch tracer = FETCH_REGISTRY_TIMER.start();
        try {
            //获取本地缓存
            Applications applications = getApplications();
      //如果增量拉取被禁用或是第一次拉取,全量拉取server端已经注册的服务实例信息
            if (clientConfig.shouldDisableDelta()
                    || (!Strings.isNullOrEmpty(clientConfig.getRegistryRefreshSingleVipAddress()))
                    || forceFullRegistryFetch
                    || (applications == null)
                    || (applications.getRegisteredApplications().size() == 0)
                    || (applications.getVersion() == -1)) //Client application does not have latest library supporting delta
            {
                //获取全部实例
                getAndStoreFullRegistry();
            } else {
              //增量拉取服务实例
                getAndUpdateDelta(applications);
            }
            applications.setAppsHashCode(applications.getReconcileHashCode());
            logTotalInstances();
        } catch (Throwable e) {
            return false;
        } finally {
            if (tracer != null) {
                tracer.stop();
            }
        }
        // 刷新本地缓存
        onCacheRefreshed();
        // 基于缓存中的实例数据更新远程实例状态, (发布StatusChangeEvent)
        updateInstanceRemoteStatus();
       // 注册表拉取成功后返回true
        return true;
    }

全量获取最终调用

EurekaHttpResponse<Applications> httpResponse = clientConfig.getRegistryRefreshSingleVipAddress() == null
                ? eurekaTransport.queryClient.getApplications(remoteRegionsRef.get())
                : eurekaTransport.queryClient.getVip(clientConfig.getRegistryRefreshSingleVipAddress(), remoteRegionsRef.get());

增量获取

EurekaHttpResponse<Applications> httpResponse = eurekaTransport.queryClient.getDelta(remoteRegionsRef.get());

可以看出,客户端与服务端通信底层是EurekaTransport在提供支持。


2.1.3 initScheduledTasks

在此之前有必要说说:TimedSupervisorTask。 TimedSupervisorTask 是自动调节间隔的周期性任务,当不超时,将以初始化的间隔执行。当任务超时时,将下一个周期的间隔调大。每次超时都会增大相应倍数,直到外部设置的最大参数。一旦新任务不再超时,间隔自动恢复默认值。

也就是说,这是一个具有自适应的周期性任务。(非常棒的设计啊)

private void initScheduledTasks() {
    //1.如果获取服务列表,则创建周期性缓存更新(即获取服务列表任务)任务
        if (clientConfig.shouldFetchRegistry()) {
          //初始间隔时间(默认30秒)
            int registryFetchIntervalSeconds = clientConfig.getRegistryFetchIntervalSeconds();
            //最大倍数 默认10倍
            int expBackOffBound = clientConfig.getCacheRefreshExecutorExponentialBackOffBound();
            //执行TimedSupervisorTask ,监督CacheRefreshThread任务的执行。
            //具体执行线程池cacheRefreshExecutor,具体任务CacheRefreshThread
            scheduler.schedule(
                    new TimedSupervisorTask(
                            "cacheRefresh",
                            scheduler,
                            cacheRefreshExecutor,
                            registryFetchIntervalSeconds,
                            TimeUnit.SECONDS,
                            expBackOffBound,
                            new CacheRefreshThread()//缓存刷新,调用fetchRegistry()获取服务列表
                    ),
                    registryFetchIntervalSeconds, TimeUnit.SECONDS);
        }
    //2. 如何注册,就创建周期性续租任务,维持心跳。
        if (clientConfig.shouldRegisterWithEureka()) {
          //心跳间隔,默认30秒。
            int renewalIntervalInSecs = instanceInfo.getLeaseInfo().getRenewalIntervalInSecs();
            //最大倍数 默认10倍
            int expBackOffBound = clientConfig.getHeartbeatExecutorExponentialBackOffBound();
            //执行TimedSupervisorTask ,监督HeartbeatThread任务的执行。
            //具体执行线程池heartbeatExecutor,具体任务HeartbeatThread
            scheduler.schedule(
                    new TimedSupervisorTask(
                            "heartbeat",
                            scheduler,
                            heartbeatExecutor,
                            renewalIntervalInSecs,
                            TimeUnit.SECONDS,
                            expBackOffBound,
                            new HeartbeatThread()
                    ),
                    renewalIntervalInSecs, TimeUnit.SECONDS);
            //3.创建应用实例信息复制器。
            instanceInfoReplicator = new InstanceInfoReplicator(
                    this,
                    instanceInfo,
                    clientConfig.getInstanceInfoReplicationIntervalSeconds(),
                    2); // burstSize
      //4.创建状态改变监听器,监听StatusChangeEvent 
            statusChangeListener = new ApplicationInfoManager.StatusChangeListener() {
                @Override
                public String getId() {
                    return "statusChangeListener";
                }
                @Override
                public void notify(StatusChangeEvent statusChangeEvent) {
                    if (InstanceStatus.DOWN == statusChangeEvent.getStatus() ||
                            InstanceStatus.DOWN == statusChangeEvent.getPreviousStatus()) {
                        // log at warn level if DOWN was involved
                        logger.warn("Saw local status change event {}", statusChangeEvent);
                    } else {
                        logger.info("Saw local status change event {}", statusChangeEvent);
                    }
                    //状态有变化,使用信息复制器,执行一个任务,更新状态变化到注册中心
                    instanceInfoReplicator.onDemandUpdate();
                }
            };
      //是否关注状态变化,将监听器添加到applicationInfoManager
            if (clientConfig.shouldOnDemandUpdateStatusChange()) {
                applicationInfoManager.registerStatusChangeListener(statusChangeListener);
            }
            // 启动InstanceInfo复制器
       instanceInfoReplicator.start(clientConfig.getInitialInstanceInfoReplicationIntervalSeconds());
        } else {
            logger.info("Not registering with Eureka server per configuration");
        }
    }

总结下initScheduledTasks()的工作: 如何配置获取服务

  1. 创建监控任务线程cacheRefresh,监督服务获取CacheRefreshThread(DiscoveryClient-CacheRefreshExecutor-%d)线程的执行,默认每30秒执行一次。获取服务列表更新到本地缓存。任务内容refreshRegistry,本地缓存localRegionApps

如何配置注册,

  1. 创建监控任务线程"heartbeat",监督续约任务HeartbeatThread(DiscoveryClient-HeartbeatExecutor-%d)的执行,默认每30秒执行一次。任务内容为renew()
  2. 创建实例状态监听器,监听当前实例的状态变化,并通过InstanceInfo复制器,执行onDemandUpdate()方法,更新变化到远程server
  3. 启动InstanceInfo复制器定时线程(DiscoveryClient-InstanceInfoReplicator-%d),定时(默认40秒)检测当前实例的DataCenterInfo、LeaseInfo、InstanceStatus,如果有变更,执行InstanceInfoReplicator.this.run()方法将变更信息同步到server

下面我们看看这几个重要的任务内容:

  • refreshRegistry刷新缓存: refreshRegistry最终调用fetchRegistry获取服务列表,更新本地缓存。fetchRegistry在DiscoveryClient初始化时,主动获取一次;之后都是定时获取。
  • renew() 续约:通过eurekaTransport.registrationClient.sendHeartBeat向server发送当前实例信息
  • InstanceInfoReplicator.onDemandUpdate() 状态更新: 一旦有状态变化,停掉定时复制线程,立刻把状态更新到server.  最终调用的是InstanceInfoReplicator.this.run()
  • InstanceInfoReplicator.this.run() 复制当前实例信息到Server: 状态变化时,立即执行;平时每40秒执行一次。


相关文章
|
监控 Java API
Spring Boot 3.2 结合 Spring Cloud 微服务架构实操指南 现代分布式应用系统构建实战教程
Spring Boot 3.2 + Spring Cloud 2023.0 微服务架构实践摘要 本文基于Spring Boot 3.2.5和Spring Cloud 2023.0.1最新稳定版本,演示现代微服务架构的构建过程。主要内容包括: 技术栈选择:采用Spring Cloud Netflix Eureka 4.1.0作为服务注册中心,Resilience4j 2.1.0替代Hystrix实现熔断机制,配合OpenFeign和Gateway等组件。 核心实操步骤: 搭建Eureka注册中心服务 构建商品
1777 3
|
负载均衡 Java API
《深入理解Spring》Spring Cloud 构建分布式系统的微服务全家桶
Spring Cloud为微服务架构提供一站式解决方案,涵盖服务注册、配置管理、负载均衡、熔断限流等核心功能,助力开发者构建高可用、易扩展的分布式系统,并持续向云原生演进。
|
负载均衡 Dubbo Java
Spring Cloud Alibaba与Spring Cloud区别和联系?
Spring Cloud Alibaba与Spring Cloud区别和联系?
|
前端开发 Java Nacos
🛡️Spring Boot 3 整合 Spring Cloud Gateway 工程实践
本文介绍了如何使用Spring Cloud Alibaba 2023.0.0.0技术栈构建微服务网关,以应对微服务架构中流量治理与安全管控的复杂性。通过一个包含鉴权服务、文件服务和主服务的项目,详细讲解了网关的整合与功能开发。首先,通过统一路由配置,将所有请求集中到网关进行管理;其次,实现了限流防刷功能,防止恶意刷接口;最后,添加了登录鉴权机制,确保用户身份验证。整个过程结合Nacos注册中心,确保服务注册与配置管理的高效性。通过这些实践,帮助开发者更好地理解和应用微服务网关。
2821 0
🛡️Spring Boot 3 整合 Spring Cloud Gateway 工程实践
|
Java Spring 容器
springcloud-config客户端启用服务发现报错找不到bean EurekaHttpClient
解决 Spring Cloud Config 客户端启用服务发现时报错找不到 bean `EurekaHttpClient` 的问题,主要涉及版本兼容性、依赖配置和正确的配置文件设置。通过检查依赖版本、添加必要的依赖项、配置文件的正确性以及启用服务发现注解,可以有效解决此问题。确保日志中没有其他错误信息也是关键步骤之一。通过这些方法,可以确保 Spring Cloud Config 与 Eureka 客户端正常工作。
454 6
|
人工智能 安全 Java
AI 时代:从 Spring Cloud Alibaba 到 Spring AI Alibaba
本次分享由阿里云智能集团云原生微服务技术负责人李艳林主讲,主题为“AI时代:从Spring Cloud Alibaba到Spring AI Alibaba”。内容涵盖应用架构演进、AI agent框架发展趋势及Spring AI Alibaba的重磅发布。分享介绍了AI原生架构与传统架构的融合,强调了API优先、事件驱动和AI运维的重要性。同时,详细解析了Spring AI Alibaba的三层抽象设计,包括模型支持、工作流智能体编排及生产可用性构建能力,确保安全合规、高效部署与可观测性。最后,结合实际案例展示了如何利用私域数据优化AI应用,提升业务价值。
2133 4
|
消息中间件 监控 Java
如何将Spring Boot + RabbitMQ应用程序部署到Pivotal Cloud Foundry (PCF)
如何将Spring Boot + RabbitMQ应用程序部署到Pivotal Cloud Foundry (PCF)
588 6
|
负载均衡 Java 开发者
深入探索Spring Cloud与Spring Boot:构建微服务架构的实践经验
深入探索Spring Cloud与Spring Boot:构建微服务架构的实践经验
1088 5
|
Java 关系型数据库 MySQL
如何将Spring Boot + MySQL应用程序部署到Pivotal Cloud Foundry (PCF)
如何将Spring Boot + MySQL应用程序部署到Pivotal Cloud Foundry (PCF)
479 5