美文网首页
深入理解Eureka Server状态计算规则(十一)

深入理解Eureka Server状态计算规则(十一)

作者: sharedCode | 来源:发表于2018-08-09 10:17 被阅读0次

    简要

    深入理解Eureka Server覆盖状态(九)这一篇文章中,我们介绍了Eureka Server的覆盖状态,但是覆盖状态设置了之后
    Eureka在使用的时候都会通过getOverriddenInstanceStatus()这个方法来计算实例的最终状态,那么他计算的规则是
    什么呢,本篇文章主要讲的就是这个。

    代码回顾

    在注册的时候,计算实例的最终状态的代码如下,

    public void register(InstanceInfo registrant, int leaseDuration, boolean isReplication) {
        try {
             
            // .....省略N多代码
            // 判断instance的的覆盖状态是否等于UNKONW (默认状态下就是等于UNKONW)
            if (!InstanceStatus.UNKNOWN.equals(registrant.getOverriddenStatus())) {
                // 如果不等于,则说明被修改过,放入overriddenInstanceStatusMap
                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());
                }
            }
            // overriddenInstanceStatusMap 里面是否存在这个instanceId的覆盖状态
            InstanceStatus overriddenStatusFromMap = overriddenInstanceStatusMap.get(registrant.getId());
            // 如果存在,则设置进去
            if (overriddenStatusFromMap != null) {
                logger.info("Storing overridden status {} from map", overriddenStatusFromMap);
                registrant.setOverriddenStatus(overriddenStatusFromMap);
            }
     
            //计算实例的最终状态。
            InstanceStatus overriddenInstanceStatus = getOverriddenInstanceStatus(registrant, existingLease, isReplication);
            registrant.setStatusWithoutDirty(overriddenInstanceStatus);
     
          
            // .....省略N多代码
        } finally {
            read.unlock();
        }
    }
    

    说明:

    由上面的代码可以很清晰的看出,在Eureka注册时候,先对覆盖状态做了一系列判断,对是否拥有覆盖状态做了初始化,

    如果有,则设置覆盖状态, 最终调用了getOverriddenInstanceStatus来计算实例的最终状态

    protected InstanceInfo.InstanceStatus getOverriddenInstanceStatus(InstanceInfo r,
                                                                    Lease<InstanceInfo> existingLease,
                                                                    boolean isReplication) {
        // 获取匹配规则
        InstanceStatusOverrideRule rule = getInstanceInfoOverrideRule();
        // 规则匹配
        return rule.apply(r, existingLease, isReplication).status();
    }
    

    获取匹配规则 : getInstanceInfoOverrideRule()的实现在AbstractInstanceRegistry的子类PeerAwareInstanceRegistryImpl里面。

    @Inject
    public PeerAwareInstanceRegistryImpl(
            EurekaServerConfig serverConfig,
            EurekaClientConfig clientConfig,
            ServerCodecs serverCodecs,
            EurekaClient eurekaClient
        ) {
        super(serverConfig, clientConfig, serverCodecs);
        this.eurekaClient = eurekaClient;
        this.numberOfReplicationsLastMin = new MeasuredRate(1000 * 60 * 1);
        // 设置状态匹配规则。 
        this.instanceStatusOverrideRule = new FirstMatchWinsCompositeRule(new DownOrStartingRule(),
                new OverrideExistsRule(overriddenInstanceStatusMap), new LeaseExistsRule());
    }
    
    
    @Override
    protected InstanceStatusOverrideRule getInstanceInfoOverrideRule() {
        return this.instanceStatusOverrideRule;
    }
    

    在PeerAwareInstanceRegistryImpl这个类加载的时候,设置了状态的匹配规则(FirstMatchWinsCompositeRule ),同时

    传入了三个参数,

    DownOrStartingRule,

    OverrideExistsRule, (传入了覆盖状态的缓存MAP)

    LeaseExistsRule

    接下来直接看这个类的代码即可。

    FirstMatchWinsCompositeRule

    public FirstMatchWinsCompositeRule(InstanceStatusOverrideRule... rules) {
        // 将 传入的规则实例匹配给rules
        this.rules = rules;
        // 设置默认的匹配规则
        this.defaultRule = new AlwaysMatchInstanceStatusRule();
       
        // 循环得到匹配规则的名字
        List<String> ruleNames = new ArrayList<>(rules.length+1);
        for (int i = 0; i < rules.length; ++i) {
            ruleNames.add(rules[i].toString());
        }
        ruleNames.add(defaultRule.toString());
        compositeRuleName = ruleNames.toString();
    }
    // 具体匹配状态的方法,主要是讲这三个方法。
    @Override
    public StatusOverrideResult apply(InstanceInfo instanceInfo,
                                      Lease<InstanceInfo> existingLease,
                                      boolean isReplication) {
        for (int i = 0; i < this.rules.length; ++i) {
            // 调用具体规则匹配状态,其实就是构造方法里面传入的那三个规则
            StatusOverrideResult result = this.rules[i].apply(instanceInfo, existingLease, isReplication);
            // 匹配成功,则返回
            if (result.matches()) {
                return result;
            }
        }
        // 如果以上都没有匹配成功,则使用该规则进行匹配
        return defaultRule.apply(instanceInfo, existingLease, isReplication);
    }
    

    说明:

    在apply方法里面,循环调用rules的apply方法,直到匹配成功 。 通过PeerAwareInstanceRegistryImpl类中创建FirstMatchWinsCompositeRule

    对象的代码,我们可以知道,具体的匹配规则有三个,加上默认的匹配规则,也就是有四个,他们分别是:

    按执行顺序排:

    DownOrStartingRule,

    OverrideExistsRule, (传入了覆盖状态的缓存MAP)

    LeaseExistsRule

    AlwaysMatchInstanceStatusRule

    DownOrStartingRule

    public StatusOverrideResult apply(InstanceInfo instanceInfo,
                                      Lease<InstanceInfo> existingLease,
                                      boolean isReplication) {
        // ReplicationInstance is DOWN or STARTING - believe that, but when the instance says UP, question that
        // The client instance sends STARTING or DOWN (because of heartbeat failures), then we accept what
        // the client says. The same is the case with replica as well.
        // The OUT_OF_SERVICE from the client or replica needs to be confirmed as well since the service may be
        // currently in SERVICE
        if ((!InstanceInfo.InstanceStatus.UP.equals(instanceInfo.getStatus()))
                && (!InstanceInfo.InstanceStatus.OUT_OF_SERVICE.equals(instanceInfo.getStatus()))) {
            logger.debug("Trusting the instance status {} from replica or instance for instance {}",
                    instanceInfo.getStatus(), instanceInfo.getId());
            return StatusOverrideResult.matchingStatus(instanceInfo.getStatus());
        }
        return StatusOverrideResult.NO_MATCH;
    }
    

    从类名上理解,这个类就是负责处理 DOWN,STRATING这两个状态匹配的, 从上面的apply代码上来看,如果instanceInfo的状态不等于UP

    同时也不等于OUT_OF_SERVICE , 那么就就匹配成功,其实说白了,不等于UP和OUT_OF_SERVICE , 其实也就是等于DOWN和STRATING。

    如果匹配成功,则返回instance的状态,匹配成功。

    PS: instanceInfo 为客户端传过来的,也就说客户端说DOWN了或者正在启动,那么服务端是直接会信任的。

    OverrideExistsRule

    public OverrideExistsRule(Map<String, InstanceInfo.InstanceStatus> statusOverrides) {
        this.statusOverrides = statusOverrides;
    }
    
    @Override
    public StatusOverrideResult apply(InstanceInfo instanceInfo, Lease<InstanceInfo> existingLease, boolean isReplication) {
        // 根据实例ID从覆盖状态MAP里面获取该实例的覆盖状态。
        InstanceInfo.InstanceStatus overridden = statusOverrides.get(instanceInfo.getId());
        // 覆盖状态不为空
        if (overridden != null) {
            logger.debug("The instance specific override for instance {} and the value is {}",
                    instanceInfo.getId(), overridden.name());
            // 匹配成功,返回覆盖状态
            return StatusOverrideResult.matchingStatus(overridden);
        }
        return StatusOverrideResult.NO_MATCH;
    }
    

    步骤说明:

    1.根据实例ID从覆盖状态MAP里面获取该实例的覆盖状态。

    2.匹配成功,返回覆盖状态

    PS: 也许有人会感觉到比较疑惑, 这里的statusOverrides只不过是在实例化OverrideExistsRule这个类的时候传入了overriddenInstanceStatusMap,

    后续为某个实例添加了覆盖状态,statusOverrudes怎么能感知到呢? 因为overriddenInstanceStatusMap 本质上是使用了gauva的缓存,所以statusOverrides指向的也是gauva的缓存,所以是能立马感知到的,因为本身就是一个东西

    LeaseExistsRule

    @Override
    public StatusOverrideResult apply(InstanceInfo instanceInfo,
                                      Lease<InstanceInfo> existingLease,
                                      boolean isReplication) {
        // This is for backward compatibility until all applications have ASG
        // names, otherwise while starting up
        // the client status may override status replicated from other servers
        // 判断是否是Eureka Server发过来的复制请求
        if (!isReplication) {
            // 判断本地的Instance是否为空,不为空这获取existingStatus
            InstanceInfo.InstanceStatus existingStatus = null;
            if (existingLease != null) {
                existingStatus = existingLease.getHolder().getStatus();
            }
            // Allow server to have its way when the status is UP or OUT_OF_SERVICE
            // existingStatus 不为空,并且 existingStatus 等于UP或者OUT_OF_SERVICE 
            // 如果满足上述条件,则匹配成功,返回existingStatus
            if ((existingStatus != null)
                    && (InstanceInfo.InstanceStatus.OUT_OF_SERVICE.equals(existingStatus)
                    || InstanceInfo.InstanceStatus.UP.equals(existingStatus))) {
                logger.debug("There is already an existing lease with status {}  for instance {}",
                        existingLease.getHolder().getStatus().name(),
                        existingLease.getHolder().getId());
                return StatusOverrideResult.matchingStatus(existingLease.getHolder().getStatus());
            }
        }
        return StatusOverrideResult.NO_MATCH;
    }
    

    步骤说明:

    1.判断是否是Eureka Server发过来的复制请求 ,isReplication = true 表示是Eureka Server的复制请求

    2.获取Eureka Server本地已经存在的instance信息,获取其状态

    3.判断状态是否为空

    4.判断状态是否等于UP 或者OUT_OF_SERVICE

    5.匹配成功,则返回本地的instanceInfo的status

    AlwaysMatchInstanceStatusRule

    
    @Override
    public StatusOverrideResult apply(InstanceInfo instanceInfo,
                                      Lease<InstanceInfo> existingLease,
                                      boolean isReplication) {
        logger.debug("Returning the default instance status {} for instance {}", instanceInfo.getStatus(),
                instanceInfo.getId());
        return StatusOverrideResult.matchingStatus(instanceInfo.getStatus());
    }
    

    当以上三个规则全部匹配不成功的时候,则直接使用这个规则匹配,这个规则会直接信任客户端发过来的

    instance的状态

    状态匹配流程

    image2018-5-31_11-5-0.png

    1.使用DownOrStartingRule做匹配,匹配客户端传过来的instanceIInfo的status是否等于DOWN或STARTING , 如果是,则匹配成功

    2.OverrideExistsRule规则, 判断该实例是否存在覆盖状态,如果存在,则直接返回覆盖状态,以覆盖状态为准

    3.LeaseExistsRule , 判断Eureka Server本地的实例状态是否等于UP或OUT_OF_SERVICE ,如果等于,则返回本地实例的状态

    4.AlwaysMatchInstanceStatusRule直接信任客户端传过来的实例信息。

    相关文章

      网友评论

          本文标题:深入理解Eureka Server状态计算规则(十一)

          本文链接:https://www.haomeiwen.com/subject/falqbftx.html