Eureka核⼼源码剖析

目录

一. Eureka Server启动过程

观察类头分析

三个关注点

(一)关注点1

(二)关注点2

(三)关注点3

二. Eureka Server服务接⼝暴露策略

三. Eureka Server服务注册接⼝(接受客户端注册服务)

四. Eureka Server服务续约接⼝(接受客户端续约)

五. Eureka Client注册服务

(一)读取配置⽂件

 (二)启动时从EurekaServer获取服务实例信息

 (三)注册⾃⼰到EurekaServer

(四)开启⼀些定时任务(⼼跳续约,刷新本地服务缓存列表)

六. Eureka Client⼼跳续约

七. Eureka Client下架服务


一. Eureka Server启动过程

⼊⼝:SpringCloud充分利⽤了SpringBoot的⾃动装配的特点

  • 观察eureka-serverjar包,发现在META-INF下⾯有配置⽂件spring.factories

 springboot应⽤启动时会加载EurekaServerAutoConfifiguration⾃动配置类

  • EurekaServerAutoConfifiguration

观察类头分析

三个关注点

----------------------------------------------------------------------------------------------------------------------------------------

 ----------------------------------------------------------------------------------------------------------------------------------------

(一)关注点1

上图中的  1、需要有⼀个marker bean,才能装配Eureka Server,那么这个marker
其实是由@EnableEurekaServer注解决定的

 

 

也就是说只有添加了 @EnableEurekaServer 注解,才会有后续的动作,这是成为⼀
EurekaServer 的前提
---------------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------------

(二)关注点2

2)上图中的 2 、 关注EurekaServerAutoConfifiguration

 

 

 

 回到主配置类中EurekaServerAutoConfifiguration类中找到:

进入到DefaultEurekaServerContext 这个类中,继续,找到initialize这个方法 

 回到主配置类DefaultEurekaServerContext 中 关注如下两个Bean:

 

----------------------------------------------------------------------------------------------------------------------------------------

 ----------------------------------------------------------------------------------------------------------------------------------------

(三)关注点3

3)  上图中3关注EurekaServerInitializerConfifiguration

 

 

重点关注,进⼊org.springframework.cloud.netflflix.eureka.server.EurekaServerBootstrap#conte
xtInitialized

 重点关注initEurekaServerContext()

 研究⼀下上图中的syncUp⽅法,进入实现类PeerAwareInstanceRegistryImpl :

 

继续研究 com.netflflix.eureka.registry.AbstractInstanceRegistry#register (提供实
例注册功能)

 

继续研究com.netflflix.eureka.registry.PeerAwareInstanceRegistryImpl#openForTraffiffiffic

 

进⼊ postInit() ⽅法查看

 

二. Eureka Server服务接⼝暴露策略

Eureka Server 启动过程中主配置类注册了 Jersey 框架(是⼀个发布 restful ⻛格接
⼝的框架,类似于我们的 springmvc
EurekaServerAutoConfiguration主配置类中找到如下两个 被@Bean标注的方法:

 注⼊的Jersey细节

点击查看EUREKA_PACKAGES,看看扫描的包路径:

 

 对外提供的接⼝服务,在Jersey中叫做资源

 

这些就是使⽤ Jersey 发布的供 Eureka Client 调⽤的 Restful ⻛格服务接⼝(完成服务
注册、⼼跳续约等接⼝)

三. Eureka Server服务注册接⼝(接受客户端注册服务)

上图中扫描包路径下的ApplicationResource 类的 addInstance() ⽅法中代码: registry.register(info,
"true".equals(isReplication));

 

com.netflflix.eureka.registry.PeerAwareInstanceRegistryImpl#register - 注册服务
信息并同步到其它 Eureka 节点

AbstractInstanceRegistry#register() :注册,实例信息存储到注册表是⼀个
ConcurrentHashMap
/**
     * Registers a new instance with a given duration.
     *
     * @see com.netflix.eureka.lease.LeaseManager#register(java.lang.Object, int, boolean)
     */
    public void register(InstanceInfo registrant, int leaseDuration, boolean isReplication) {
        try {
            read.lock(); //读锁
            // registry是保存所有应⽤实例信息的
            // Map:ConcurrentHashMap<String, Map<String, Lease<InstanceInfo>>>
            // 从registry中获取当前appName的所有实例信息
            Map<String, Lease<InstanceInfo>> gMap = registry.get(registrant.getAppName());
            REGISTER.increment(isReplication);//注册统计+1
            // 如果当前appName实例信息为空,新建Map
            if (gMap == null) {
                final ConcurrentHashMap<String, Lease<InstanceInfo>> gNewMap = new ConcurrentHashMap<String, Lease<InstanceInfo>>();
                gMap = registry.putIfAbsent(registrant.getAppName(), gNewMap);
                if (gMap == null) {
                    gMap = gNewMap;
                }
            }
            // 获取实例的Lease租约信息
            Lease<InstanceInfo> existingLease = gMap.get(registrant.getId());
            // Retain the last dirty timestamp without overwriting it, if there is already a lease
            // 如果已经有租约,则保留最后⼀个脏时间戳⽽不覆盖它
            // (⽐较当前请求实例租约 和 已有租约 的LastDirtyTimestamp,选择靠
            // 后的)
            if (existingLease != null && (existingLease.getHolder() != null)) {
                Long existingLastDirtyTimestamp = existingLease.getHolder().getLastDirtyTimestamp();
                Long registrationLastDirtyTimestamp = registrant.getLastDirtyTimestamp();
                logger.debug("Existing lease found (existing={}, provided={}", existingLastDirtyTimestamp, registrationLastDirtyTimestamp);

                // this is a > instead of a >= because if the timestamps are equal, we still take the remote transmitted
                // InstanceInfo instead of the server local copy.
                if (existingLastDirtyTimestamp > registrationLastDirtyTimestamp) {
                    logger.warn("There is an existing lease and the existing lease's dirty timestamp {} is greater" +
                            " than the one that is being registered {}", existingLastDirtyTimestamp, registrationLastDirtyTimestamp);
                    logger.warn("Using the existing instanceInfo instead of the new instanceInfo as the registrant");
                    registrant = existingLease.getHolder();
                }
            } else {
                // The lease does not exist and hence it is a new registration
                // 如果之前不存在实例的租约,说明是新实例注册
                // expectedNumberOfRenewsPerMin期待的每分钟续约数+2(因为30s⼀个)
                // 并更新numberOfRenewsPerMinThreshold每分钟续约阀值(85%)
                synchronized (lock) {
                    if (this.expectedNumberOfClientsSendingRenews > 0) {
                        // Since the client wants to register it, increase the number of clients sending renews
                        this.expectedNumberOfClientsSendingRenews = this.expectedNumberOfClientsSendingRenews + 1;
                        updateRenewsPerMinThreshold();
                    }
                }
                logger.debug("No previous lease information found; it is new registration");
            }
            Lease<InstanceInfo> lease = new Lease<InstanceInfo>(registrant, leaseDuration);
            if (existingLease != null) {
                lease.setServiceUpTimestamp(existingLease.getServiceUpTimestamp());
            }
            //当前实例信息放到维护注册信息的Map
            gMap.put(registrant.getId(), lease);
            // 同步维护最近注册队列
            synchronized (recentRegisteredQueue) {
                recentRegisteredQueue.add(new Pair<Long, String>(
                        System.currentTimeMillis(),
                        registrant.getAppName() + "(" + registrant.getId() + ")"));
            }
            // This is where the initial state transfer of overridden status happens
            // 如果当前实例已经维护了OverriddenStatus,将其也放到此
            // EurekaServer的overriddenInstanceStatusMap中
            if (!InstanceStatus.UNKNOWN.equals(registrant.getOverriddenStatus())) {
                logger.debug("Found overridden status {} for instance {}. Checking to see if needs to be add to the "
                        + "overrides", registrant.getOverriddenStatus(), registrant.getId());
                if (!overriddenInstanceStatusMap.containsKey(registrant.getId())) {
                    logger.info("Not found overridden id {} and hence adding it", registrant.getId());
                    overriddenInstanceStatusMap.put(registrant.getId(), registrant.getOverriddenStatus());
                }
            }
            InstanceStatus overriddenStatusFromMap = overriddenInstanceStatusMap.get(registrant.getId());
            if (overriddenStatusFromMap != null) {
                logger.info("Storing overridden status {} from map", overriddenStatusFromMap);
                registrant.setOverriddenStatus(overriddenStatusFromMap);
            }

            // Set the status based on the overridden status rules
            // 根据overridden status规则,设置状态
            InstanceStatus overriddenInstanceStatus = getOverriddenInstanceStatus(registrant, existingLease, isReplication);
            registrant.setStatusWithoutDirty(overriddenInstanceStatus);

            // If the lease is registered with UP status, set lease service up timestamp
            // 如果租约以UP状态注册,设置租赁服务时间戳
            if (InstanceStatus.UP.equals(registrant.getStatus())) {
                lease.serviceUp();
            }
            //ActionType为ADD
            registrant.setActionType(ActionType.ADDED);
            //维护recentlyChangedQueue
            recentlyChangedQueue.add(new RecentlyChangedItem(lease));
            //更新最后更新时间
            registrant.setLastUpdatedTimestamp();
            // 使当前应⽤的ResponseCache失效
            invalidateCache(registrant.getAppName(), registrant.getVIPAddress(), registrant.getSecureVipAddress());
            logger.info("Registered instance {}/{} with status {} (replication={})",
                    registrant.getAppName(), registrant.getId(), registrant.getStatus(), isReplication);
        } finally {
            read.unlock();//读锁
        }
    }

 再查看上图的replicateToPeers

PeerAwareInstanceRegistryImpl#replicateToPeers() :复制到 Eureka 对等节点

 

    /**
     * Replicates all eureka actions to peer eureka nodes except for replication
     * traffic to this node.
     *
     */
    private void replicateToPeers(Action action, String appName, String id,
                                  InstanceInfo info /* optional */,
                                  InstanceStatus newStatus /* optional */, boolean isReplication) {
        Stopwatch tracer = action.getTimer().start();
        try {
            // 如果是复制操作(针对当前节点,false)
            if (isReplication) {
                numberOfReplicationsLastMin.increment();
            }
            // If it is a replication already, do not replicate again as this will create a poison replication
            // 如果它已经是复制,请不要再次复制,直接return
            if (peerEurekaNodes == Collections.EMPTY_LIST || isReplication) {
                return;
            }
            // 遍历集群所有节点(除当前节点外)
            for (final PeerEurekaNode node : peerEurekaNodes.getPeerEurekaNodes()) {
                // If the url represents this host, do not replicate to yourself.
                if (peerEurekaNodes.isThisMyUrl(node.getServiceUrl())) {
                    continue;
                }
                // 复制Instance实例操作到某个node节点
                replicateInstanceActionsToPeers(action, appName, id, info, newStatus, node);
            }
        } finally {
            tracer.stop();
        }
    }

继续查看PeerAwareInstanceRegistryImpl#replicateInstanceActionsToPeers

四. Eureka Server服务续约接⼝(接受客户端续约)

扫描包中InstanceResource renewLease ⽅法中完成客户端的⼼跳(续约)处理,关键代
码: registry.renew(app.getName(), id, isFromReplicaNode);

 

 com.netflflix.eureka.registry.PeerAwareInstanceRegistryImpl#renew

 上图继续调用replicateToPeers方法,在该方法中又调用replicateInstanceActionsToPeers() 复制Instance实例操作到其它节点。

renew()⽅法中—>leaseToRenew.renew()—>对最后更新时间戳进⾏更新

五. Eureka Client注册服务

启动过程: Eureka 客户端在启动时也会装载很多配置类,我们通过 spring-cloud
netflflix-eureka-client-2.1.0.RELEASE.jar 下的 spring.factories ⽂件可以看到加载的配
置类

 引⼊jar就会被⾃动装配,分析EurekaClientAutoConfifiguration类头

 如果不想作为客户端,可以设置eureka.client.enabled=false

 回到主配置类EurekaClientAutoConfifiguration

思考: EurekaClient 启动过程要做什么事情?
1 )读取配置⽂件
2 )启动时从 EurekaServer 获取服务实例信息
3 )注册⾃⼰到 EurekaServer addInstance
4 )开启⼀些定时任务(⼼跳续约,刷新本地服务缓存列表)

(一)读取配置⽂件

 (二)启动时从EurekaServer获取服务实例信息

 

@Bean(destroyMethod = "shutdown")
		@ConditionalOnMissingBean(value = EurekaClient.class, search = SearchStrategy.CURRENT)
		@org.springframework.cloud.context.config.annotation.RefreshScope
		@Lazy
		public EurekaClient eurekaClient(ApplicationInfoManager manager, EurekaClientConfig config, EurekaInstanceConfig instance,
										 @Autowired(required = false) HealthCheckHandler healthCheckHandler) {
			//If we use the proxy of the ApplicationInfoManager we could run into a problem
			//when shutdown is called on the CloudEurekaClient where the ApplicationInfoManager bean is
			//requested but wont be allowed because we are shutting down.  To avoid this we use the
			//object directly.
			ApplicationInfoManager appManager;
			if(AopUtils.isAopProxy(manager)) {
				appManager = ProxyUtils.getTargetObject(manager);
			} else {
				appManager = manager;
			}
			CloudEurekaClient cloudEurekaClient = new CloudEurekaClient(appManager, config, this.optionalArgs,
					this.context);
			cloudEurekaClient.registerHealthCheck(healthCheckHandler);
			return cloudEurekaClient;
		}

进入上图 CloudEurekaClient构造方法

观察⽗类DiscoveryClient() 

 在另外⼀个构造器中 :进入DiscoveryClient类的DiscoveryClient方法,并找到如下

 进入fetchRegistry方法继续查看

 (三)注册⾃⼰到EurekaServer

DiscoveryClient类的DiscoveryClient方法,并找到如下

进入 DiscoveryClient#register方法

 底层使⽤Jersey客户端进⾏远程请求。

(四)开启⼀些定时任务(⼼跳续约,刷新本地服务缓存列表)

DiscoveryClient类的DiscoveryClient方法,并找到如下:

 点击进入initScheduledTasks方法

 点击进入CacheRefreshThread()方法


 

六. Eureka Client⼼跳续约

 回到initScheduledTasks() 方法:

 点击进入HeartbeatThread()方法

 点击进入renew()方法

 点击进入sendHeartBeat方法

 DiscoveryClient类initScheduledTasks() 方法完整代码如下:

 /**
     * Initializes all scheduled tasks.
     */
    private void initScheduledTasks() {
        if (clientConfig.shouldFetchRegistry()) {
            // registry cache refresh timer
            int registryFetchIntervalSeconds = clientConfig.getRegistryFetchIntervalSeconds();
            int expBackOffBound = clientConfig.getCacheRefreshExecutorExponentialBackOffBound();
            scheduler.schedule(
                    new TimedSupervisorTask(
                            "cacheRefresh",
                            scheduler,
                            cacheRefreshExecutor,
                            registryFetchIntervalSeconds,
                            TimeUnit.SECONDS,
                            expBackOffBound,
                            new CacheRefreshThread()
                    ),
                    registryFetchIntervalSeconds, TimeUnit.SECONDS);
        }

        if (clientConfig.shouldRegisterWithEureka()) {
            int renewalIntervalInSecs = instanceInfo.getLeaseInfo().getRenewalIntervalInSecs();
            int expBackOffBound = clientConfig.getHeartbeatExecutorExponentialBackOffBound();
            logger.info("Starting heartbeat executor: " + "renew interval is: {}", renewalIntervalInSecs);

            // Heartbeat timer
            scheduler.schedule(
                    new TimedSupervisorTask(
                            "heartbeat",
                            scheduler,
                            heartbeatExecutor,
                            renewalIntervalInSecs,
                            TimeUnit.SECONDS,
                            expBackOffBound,
                            new HeartbeatThread()
                    ),
                    renewalIntervalInSecs, TimeUnit.SECONDS);

            // InstanceInfo replicator
            instanceInfoReplicator = new InstanceInfoReplicator(
                    this,
                    instanceInfo,
                    clientConfig.getInstanceInfoReplicationIntervalSeconds(),
                    2); // burstSize

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

            if (clientConfig.shouldOnDemandUpdateStatusChange()) {
                applicationInfoManager.registerStatusChangeListener(statusChangeListener);
            }

            instanceInfoReplicator.start(clientConfig.getInitialInstanceInfoReplicationIntervalSeconds());
        } else {
            logger.info("Not registering with Eureka server per configuration");
        }
    }

七. Eureka Client下架服务

我们看com.netflflix.discovery.DiscoveryClient#shutdown

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值