十二.SpringCloud源码剖析-Eureka Server服务剔除

简介: 这一章我们来分析一下Eureka Server 的服务剔除

系列文章目录

一.SpringCloud源码剖析-Eureka核心API

二.SpringCloud源码剖析-Eureka Client 初始化过程

三.SpringCloud源码剖析-Eureka服务注册

四.SpringCloud源码剖析-Eureka服务发现

五.SpringCloud源码剖析-Eureka Client服务续约

六.SpringCloud源码剖析-Eureka Client取消注册

七.SpringCloud源码剖析-Eureka Server的自动配置

八.SpringCloud源码剖析-Eureka Server初始化流程

九.SpringCloud源码剖析-Eureka Server服务注册流程

十.SpringCloud源码剖析-Eureka Server服务续约

十一.SpringCloud源码剖析-Eureka Server服务注册表拉取

Eureka Server服务剔除

这一章我们来分析一下Eureka Server 的服务剔除,它是通过定时任务完成的,在EurekaBootStrap启动引导的initEurekaServerContext上下文初始化方法中,调用了这么一行代码registry.openForTraffic(applicationInfoManager, registryCount);在该方法中又调用了com.netflix.eureka.registry.AbstractInstanceRegistry#postInit方法来初始化服务剔除的定时任务

public abstract class AbstractInstanceRegistry implements InstanceRegistry {
   
   
    protected void postInit() {
   
   
        renewsLastMin.start();

        if (evictionTaskRef.get() != null) {
   
   
            //如果服务剔除任务不为空,就执行cancel方法,该方法把任务的状态修改为了cancel任务取消
            evictionTaskRef.get().cancel();
        }
        //创建新的服务剔除任务
        evictionTaskRef.set(new EvictionTask());
        //交给调度器去执行,延迟60s,每60s执行一次驱逐任务
        evictionTimer.schedule(evictionTaskRef.get(),
                serverConfig.getEvictionIntervalTimerInMs(),    //60s 逐出间隔计时器
                serverConfig.getEvictionIntervalTimerInMs());    
    }

/* visible for testing */ 
    class EvictionTask extends TimerTask {
   
   

        private final AtomicLong lastExecutionNanosRef = new AtomicLong(0l);

        @Override
        public void run() {
   
   
            try {
   
   
                //计算任务执行的时间偏差:补偿时间
                long compensationTimeMs = getCompensationTimeMs();
                logger.info("Running the evict task with compensationTime {}ms", compensationTimeMs);
                //执行驱逐
                evict(compensationTimeMs);
            } catch (Throwable e) {
   
   
                logger.error("Could not run the evict task", e);
            }
        }

在驱逐任务中,计算了任务执行的时间偏差即补偿时间,然后调用com.netflix.eureka.registry.AbstractInstanceRegistry#evict(long)执行服务的剔除逻辑

public void evict(long additionalLeaseMs) {
   
   
        logger.debug("Running the evict task");

        if (!isLeaseExpirationEnabled()) {
   
   
                //如果没启用租约到期,直接返回
            logger.debug("DS: lease expiration is currently disabled.");
            return;
        }

        //首先收集所有过期的服务,以随机顺序将其逐出
        // We collect first all expired items, to evict them in random order. For large eviction sets,

        // if we do not that, we might wipe out whole apps before self preservation kicks in. By randomizing it,
        // the impact should be evenly distributed across all applications.
        List<Lease<InstanceInfo>> expiredLeases = new ArrayList<>();
        //循环注册表中的所有的服务
        for (Entry<String, Map<String, Lease<InstanceInfo>>> groupEntry : registry.entrySet()) {
   
   

            Map<String, Lease<InstanceInfo>> leaseMap = groupEntry.getValue();
            if (leaseMap != null) {
   
   
            //获取到租约
                for (Entry<String, Lease<InstanceInfo>> leaseEntry : leaseMap.entrySet()) {
   
   
                    Lease<InstanceInfo> lease = leaseEntry.getValue();
                    //如果服务过期,就把服务添加到expiredLeases map中
                    if (lease.isExpired(additionalLeaseMs) && lease.getHolder() != null) {
   
   
                        expiredLeases.add(lease);
                    }
                }
            }
        }

        //为了补偿GC暂停或本地时间差异导致的剔除任务执行时间差异,使用当前注册表大小作为触发自我保存的基础
        //否则,将清除完整的注册表。
        // To compensate for GC pauses or drifting local time, we need to use current registry size as a base for
        // triggering self-preservation. Without that we would wipe out full registry.
        //注册表大小
        int registrySize = (int) getLocalRegistrySize();
        //注册表中服务的续约阈值 = 注册大小 * 0.85
        int registrySizeThreshold = (int) (registrySize * serverConfig.getRenewalPercentThreshold());
        //驱逐极限 = 注册表大小 - 注册表续约阈值 
        int evictionLimit = registrySize - registrySizeThreshold;
        //过期的服务数 和 evictionLimit  取最小 ,如果大于 0 说明需要有服务要剔除
        int toEvict = Math.min(expiredLeases.size(), evictionLimit);
        if (toEvict > 0) {
   
   
            //剔除 toEvict 个
            logger.info("Evicting {} items (expired={}, evictionLimit={})", toEvict, expiredLeases.size(), evictionLimit);
            //取随机值
            Random random = new Random(System.currentTimeMillis());
            for (int i = 0; i < toEvict; i++) {
   
   
                //选择一个随机项目(Knuth随机算法),随机剔除
                // Pick a random item (Knuth shuffle algorithm)
                int next = i + random.nextInt(expiredLeases.size() - i);
                Collections.swap(expiredLeases, i, next);
                //获取剔除服务的Lease
                Lease<InstanceInfo> lease = expiredLeases.get(i);
                //应用名
                String appName = lease.getHolder().getAppName();
                //实例ID
                String id = lease.getHolder().getId();
                //expired Counter 过期计数增加
                EXPIRED.increment();
                logger.warn("DS: Registry: expired lease for {}/{}", appName, id);            //内部取消
                internalCancel(appName, id, false);
            }
        }
    }

这里做了如下事情

  • 1.判断是否开启过期驱逐
  • 2.获取到所有的过期的服务,通过Lease.isExpired判断过期
  • 3.计算一个驱逐极限值 :min( 过期数 ,注册表服务数 - 注册表服务数 * 0.85(续约阈值百分比) )
  • 4.如果驱逐极限值 > 0 ,那就从过期的服务中随机驱逐 “驱逐极限”个服务
  • 5.调用internalCancel方法消息服务

我们可以看下Lease.isExpired是如何判断实例过期的

    /**
     * Checks if the lease of a given {@link com.netflix.appinfo.InstanceInfo} has expired or not.
     *
     * Note that due to renew() doing the 'wrong" thing and setting lastUpdateTimestamp to +duration more than
     * what it should be, the expiry will actually be 2 * duration. This is a minor bug and should only affect
     * instances that ungracefully shutdown. Due to possible wide ranging impact to existing usage, this will
     * not be fixed.
     *
     * @param additionalLeaseMs any additional lease time to add to the lease evaluation in ms.
     */
    public boolean isExpired(long additionalLeaseMs) {
   
   
        return (evictionTimestamp > 0 || System.currentTimeMillis() > (lastUpdateTimestamp + duration + additionalLeaseMs));
    }

这里给的过期计算方式是: evictionTimestamp (剔除时间戳) > 0 || 最后更新时间戳 + 租期(90s) + 补偿时间 。

但是有意思的是这个方法上的注释说了一个问题:它说由于renew()做了“错误”的事情,将lastUpdateTimestamp设置为+duration,超过了它应该的值,因此到期实际上是2 duration,这个是个小问题,没有什么影响就没做修改。意思是renew方法中的lastUpdateTimestamp时间 不应该 + duration租期时间,这超过了它应该的值,因此到期实际上是2 duration

    public void renew() {
   
   
        lastUpdateTimestamp = System.currentTimeMillis() + duration;
    }

当然这个问题没有太大影响,所以没做改正,注释上也说明白了这个问题,这个方法我们就看到这

继续看一下internalCancel内部取消服务的方法

   /**
     * {@link #cancel(String, String, boolean)} method is overridden by {@link PeerAwareInstanceRegistry}, so each
     * cancel request is replicated to the peers. This is however not desired for expires which would be counted
     * in the remote peers as valid cancellations, so self preservation mode would not kick-in.
     */
    protected boolean internalCancel(String appName, String id, boolean isReplication) {
   
   
        try {
   
   
        //上锁
            read.lock();
            //服务取消数增加
            CANCEL.increment(isReplication);
            //获取当前提出的服务
            Map<String, Lease<InstanceInfo>> gMap = registry.get(appName);
            Lease<InstanceInfo> leaseToCancel = null;
            if (gMap != null) {
   
   
                //从服务注册的map中移除掉当前服务
                leaseToCancel = gMap.remove(id);
            }
            //添加到最近取消队列
            synchronized (recentCanceledQueue) {
   
   
                recentCanceledQueue.add(new Pair<Long, String>(System.currentTimeMillis(), appName + "(" + id + ")"));
            }
            //overriddenInstanceStatusMap 服务状态map中移除当前服务
            InstanceStatus instanceStatus = overriddenInstanceStatusMap.remove(id);
            if (instanceStatus != null) {
   
   
                logger.debug("Removed instance id {} from the overridden map which has value {}", id, instanceStatus.name());
            }
            if (leaseToCancel == null) {
   
   
                //没找到服务
                CANCEL_NOT_FOUND.increment(isReplication);
                logger.warn("DS: Registry: cancel failed because Lease is not registered for: {}/{}", appName, id);
                return false;
            } else {
   
   
                //调用Lease.cancel方法

                leaseToCancel.cancel();
                //获取服务实例信息
                InstanceInfo instanceInfo = leaseToCancel.getHolder();
                String vip = null;
                String svip = null;
                if (instanceInfo != null) {
   
   
                    //实例状态修改为删除
                    instanceInfo.setActionType(ActionType.DELETED);
                    //添加最近修改队列
                    recentlyChangedQueue.add(new RecentlyChangedItem(leaseToCancel));
                    //实例信息对象修改最后修改时间
                    instanceInfo.setLastUpdatedTimestamp();
                    vip = instanceInfo.getVIPAddress();
                    svip = instanceInfo.getSecureVipAddress();
                }
                //使缓存无效,调用responseCache.invalidate让服务在缓存中失效
                invalidateCache(appName, vip, svip);
                logger.info("Cancelled instance {}/{} (replication={})", appName, id, isReplication);
                return true;
            }
        } finally {
   
   
            read.unlock();
        }
    }

这里主要是根据当前要取消的服务名从registry中查询出服务之后做了这些事情

  • 1.从registry中移除服务,
  • 2.从overriddenInstanceStatusMap状态map中移除服务状态
  • 3.添加到最近取消队列
  • 4.调用Lease.cancel方法,将租约对象中的逐出时间修改为当前时间
  • 5.修改服务的InstanceInfo的状态为DELETE
  • 6.添加到最近修改队列
  • 7.更新服务最后修改时间
  • 8.使ReponseCache缓存无效

总结

在这里插入图片描述

相关文章
|
5天前
|
Java 应用服务中间件 Nacos
Spring Cloud 常用各个组件详解及实现原理(附加源码+实现逻辑图)
Spring Cloud 常用各个组件详解及实现原理(附加源码+实现逻辑图)
39 0
|
5天前
|
监控 数据可视化 安全
一套成熟的Spring Cloud智慧工地平台源码,自主版权,开箱即用
这是一套基于Spring Cloud的智慧工地管理平台源码,具备自主版权,易于使用。平台运用现代技术如物联网、大数据等改进工地管理,服务包括建设各方,提供人员、车辆、视频监控等七大维度的管理。特色在于可视化管理、智能报警、移动办公和分布计算存储。功能涵盖劳务实名制管理、智能考勤、视频监控AI识别、危大工程监控、环境监测、材料管理和进度管理等,实现工地安全、高效的智慧化管理。
|
5天前
|
Java API 微服务
【Spring Boot系列】通过OpenAPI规范构建微服务服务接口
【4月更文挑战第5天】通过OpenAPI接口构建Spring Boot服务RestAPI接口
62 0
|
5天前
|
存储 SpringCloudAlibaba Java
【微服务 SpringCloud】实用篇 · 服务拆分和远程调用
【微服务 SpringCloud】实用篇 · 服务拆分和远程调用
20 2
|
5天前
|
监控 Java 应用服务中间件
Spring Boot 源码面试知识点
【5月更文挑战第12天】Spring Boot 是一个强大且广泛使用的框架,旨在简化 Spring 应用程序的开发过程。深入了解 Spring Boot 的源码,有助于开发者更好地使用和定制这个框架。以下是一些关键的知识点:
25 6
|
5天前
|
Java 应用服务中间件 测试技术
深入探索Spring Boot Web应用源码及实战应用
【5月更文挑战第11天】本文将详细解析Spring Boot Web应用的源码架构,并通过一个实际案例,展示如何构建一个基于Spring Boot的Web应用。本文旨在帮助读者更好地理解Spring Boot的内部工作机制,以及如何利用这些机制优化自己的Web应用开发。
32 3
|
5天前
|
存储 前端开发 Java
Spring Boot自动装配的源码学习
【4月更文挑战第8天】Spring Boot自动装配是其核心机制之一,其设计目标是在应用程序启动时,自动配置所需的各种组件,使得应用程序的开发和部署变得更加简单和高效。下面是关于Spring Boot自动装配的源码学习知识点及实战。
17 1
|
5天前
|
传感器 人工智能 前端开发
JAVA语言VUE2+Spring boot+MySQL开发的智慧校园系统源码(电子班牌可人脸识别)Saas 模式
智慧校园电子班牌,坐落于班级的门口,适合于各类型学校的场景应用,班级学校日常内容更新可由班级自行管理,也可由学校统一管理。让我们一起看看,电子班牌有哪些功能呢?
108 4
JAVA语言VUE2+Spring boot+MySQL开发的智慧校园系统源码(电子班牌可人脸识别)Saas 模式
|
5天前
|
设计模式 安全 Java
【初学者慎入】Spring源码中的16种设计模式实现
以上是威哥给大家整理了16种常见的设计模式在 Spring 源码中的运用,学习 Spring 源码成为了 Java 程序员的标配,你还知道Spring 中哪些源码中运用了设计模式,欢迎留言与威哥交流。
|
5天前
|
Java 数据安全/隐私保护 Sentinel
微服务学习 | Spring Cloud 中使用 Sentinel 实现服务限流
微服务学习 | Spring Cloud 中使用 Sentinel 实现服务限流

热门文章

最新文章