Spring Cloud Netflix-Eureka(二)、信息存储原理

Spring Cloud Netflix之Eureka源码系列文章一共分为六个片段

Spring Cloud Netflix-Eureka(一)、服务注册与发现
Spring Cloud Netflix-Eureka(二)、信息存储原理
Spring Cloud Netflix-Eureka(三)、自我保护机制
Spring Cloud Netflix-Eureka(四)、心跳续约机制
Spring Cloud Netflix-Eureka(五)、多级缓存机制
Spring Cloud Netflix-Eureka(六)、集群数据同步


Eureka Client 在启动过程中,会调用 DiscoveryClient.register() 发送服务注册请求,Eureka Server 在收到客户端的服务注册请求后,需要把信息存储到 Eureka Server 中,那它的是如何存储注册信息呢?又是以什么形式和结构进行存储呢?

Eureka Client 在启动过程中,会想服务器发送一个服务注册请求,具体代码在上一节【Spring Cloud Netflix-Eureka(一)、服务注册与发现】中分析过,调用 AbstractJerseyEurekaHttpClient 中的 EurekaHttpResponse<Void> register(InstanceInfo info) 方法。Eureka 对外提供的是一个基于 Jersey(Jersey是基于JAX-RS标准,提供REST的实现的支持) 实现的 REST 接口服务,具体核心代码在 eureka-core 包下的 resources 目录下。
在这里插入图片描述

而基于应用的服务请求,在 resources 下的 ApplicationResource 类中进行一个提供暴露。

Eureka 服务端在收到客户端的服务注册请求后,会调用 ApplicationResource 下的 addInstance() 方法。

一、Eureka 注册信息如何存储?

1.1 ApplicationResource.addInstance()

Eureka Server 中的 ApplicationResource.addInstance() 负责处理客户端的服务注册请求,具体代码如下。

@Produces({"application/xml", "application/json"})
public class ApplicationResource {
	@POST
    @Consumes({"application/json", "application/xml"})
    public Response addInstance(InstanceInfo info,
                                @HeaderParam(PeerEurekaNode.HEADER_REPLICATION) String isReplication) {
        logger.debug("Registering instance {} (replication={})", info.getId(), isReplication);
        // validate that the instanceinfo contains all the necessary required fields
        // 参数校验
        if (isBlank(info.getId())) {
            return Response.status(400).entity("Missing instanceId").build();
        } else if (isBlank(info.getHostName())) {
            return Response.status(400).entity("Missing hostname").build();
        } else if (isBlank(info.getIPAddr())) {
            return Response.status(400).entity("Missing ip address").build();
        } else if (isBlank(info.getAppName())) {
            return Response.status(400).entity("Missing appName").build();
        } else if (!appName.equals(info.getAppName())) {
            return Response.status(400).entity("Mismatched appName, expecting " + appName + " but was " + info.getAppName()).build();
        } else if (info.getDataCenterInfo() == null) {
            return Response.status(400).entity("Missing dataCenterInfo").build();
        } else if (info.getDataCenterInfo().getName() == null) {
            return Response.status(400).entity("Missing dataCenterInfo Name").build();
        }

        // handle cases where clients may be registering with bad DataCenterInfo with missing data
        DataCenterInfo dataCenterInfo = info.getDataCenterInfo();
        if (dataCenterInfo instanceof UniqueIdentifier) {
            String dataCenterInfoId = ((UniqueIdentifier) dataCenterInfo).getId();
            if (isBlank(dataCenterInfoId)) {
                boolean experimental = "true".equalsIgnoreCase(serverConfig.getExperimental("registration.validation.dataCenterInfoId"));
                if (experimental) {
                    String entity = "DataCenterInfo of type " + dataCenterInfo.getClass() + " must contain a valid id";
                    return Response.status(400).entity(entity).build();
                } else if (dataCenterInfo instanceof AmazonInfo) {
                    AmazonInfo amazonInfo = (AmazonInfo) dataCenterInfo;
                    String effectiveId = amazonInfo.get(AmazonInfo.MetaDataKey.instanceId);
                    if (effectiveId == null) {
                        amazonInfo.getMetadata().put(AmazonInfo.MetaDataKey.instanceId.getName(), info.getId());
                    }
                } else {
                    logger.warn("Registering DataCenterInfo of type {} without an appropriate id", dataCenterInfo.getClass());
                }
            }
        }

		// 调用服务注册方法,保存 InstanceInfo 对象
        registry.register(info, "true".equals(isReplication));
        return Response.status(204).build();  // 204 to be backwards compatible
    }
}

1.2 PeerAwareInstanceRegistryImpl.register(final InstanceInfo info, final boolean isReplication)

接着进入到 PeerAwareInstanceRegistryImpl 的 register(final InstanceInfo info, final boolean isReplication) 方法。

@Singleton
public class PeerAwareInstanceRegistryImpl extends AbstractInstanceRegistry implements PeerAwareInstanceRegistry {
	@Override
    public void register(final InstanceInfo info, final boolean isReplication) {
    	// 租约过期时间(默认是90s)
        int leaseDuration = Lease.DEFAULT_DURATION_IN_SECS;
        if (info.getLeaseInfo() != null && info.getLeaseInfo().getDurationInSecs() > 0) {
        	// 如果客户端有自己定义心跳超时时间,则采用客户端的
            leaseDuration = info.getLeaseInfo().getDurationInSecs();
        }
        // 节点注册:保存节点信息
        super.register(info, leaseDuration, isReplication);
        // 同步信息到其他集群节点:获得集群中的所有节点,然后逐个发起注册请求
        replicateToPeers(Action.Register, info.getAppName(), info.getId(), info, null, isReplication);
    }
}

1.3 AbstractInstanceRegistry.register(InstanceInfo registrant, int leaseDuration, boolean isReplication)

调用父类的 register(InstanceInfo registrant, int leaseDuration, boolean isReplication) 方法,完成服务注册,保存节点信息。

AbstractInstanceRegistry 类中,通过 ConcurrentHashMap<String, Map<String, Lease<InstanceInfo>>> registry = new ConcurrentHashMap<String, Map<String, Lease<InstanceInfo>>>(); 存储节点信息,其中 registry 的 key 为服务名称,value 为当前服务所有节点信息。

public abstract class AbstractInstanceRegistry implements InstanceRegistry {
	// 存储节点信息
    private final ConcurrentHashMap<String, Map<String, Lease<InstanceInfo>>> registry
            = new ConcurrentHashMap<String, Map<String, Lease<InstanceInfo>>>();
            
	/**
	 * 节点注册:保存节点信息
	 */
	public void register(InstanceInfo registrant, int leaseDuration, boolean isReplication) {
		// 加锁
        read.lock();
        try {
        	// 根据appName获取当前实例信息
            Map<String, Lease<InstanceInfo>> gMap = registry.get(registrant.getAppName());
            REGISTER.increment(isReplication);
            // 如果gMap为空,说明当前服务端没有保存该实例数据,则通过下面代码进行初始化
            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;
                }
            }
			
			// 从gMap中查询已经存在的Lease信息,Lease中文翻译为租约,
			// 实际上它把服务提供者的实例信息包装成了一个lease,里面提供了对于改服务实例的租约管理
            Lease<InstanceInfo> existingLease = gMap.get(registrant.getId());
            // Retain the last dirty timestamp without overwriting it, if there is already a lease
            // 当instance已经存在时,和客户端的instance的信息做比较,取时间最新的 instance 数据
            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 {// 如果lease不存在,保存为是一个新的实例信息

                // The lease does not exist and hence it is a new registration
                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");
            }
            // 根据registrant、leaseDuration创建一个Lease租约信息
            Lease<InstanceInfo> lease = new Lease<InstanceInfo>(registrant, leaseDuration);
            // 当原来存在Lease的信息时,设置serviceUpTimestamp, 
            // 保证服务启动的时间一直是第一次注册的那个(避免状态变更影响到服务启动时间)
            if (existingLease != null) {
                lease.setServiceUpTimestamp(existingLease.getServiceUpTimestamp());
            }

			// 保存服务实例到gMap中
            gMap.put(registrant.getId(), lease);
            
            // 添加 最近注册队列
            recentRegisteredQueue.add(new Pair<Long, String>(System.currentTimeMillis(), registrant.getAppName() + "(" + registrant.getId() + ")"));
            
            // This is where the initial state transfer of overridden status happens
            // 如果实例状态不等于UNKNOWN,则把当前实例状态添加到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
            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();
            }
            // 设置注册类型为ADDED
            registrant.setActionType(ActionType.ADDED);
            // 租约变更记录队列,记录了实例的每次变化, 用于注册信息的增量获取
            recentlyChangedQueue.add(new RecentlyChangedItem(lease));
            // 修改最后一次更新时间
            registrant.setLastUpdatedTimestamp();
            
			// 失效缓存:保证客户端获取的时候,拿去最新的数据
            invalidateCache(registrant.getAppName(), registrant.getVIPAddress(), registrant.getSecureVipAddress());
            logger.info("Registered instance {}/{} with status {} (replication={})",
                    registrant.getAppName(), registrant.getId(), registrant.getStatus(), isReplication);
        } finally {
            read.unlock();
        }
    }
}

二、EurekaServer注册信息存储总结

至此,我们就把服务注册在客户端和服务端的处理过程做了一个详细的分析,实际上在Eureka Server端,会把客户端的地址信息保存到 AbstractInstanceRegistry 中的 ConcurrentHashMap<String, Map<String, Lease<InstanceInfo>>> registry = new ConcurrentHashMap<String, Map<String, Lease<InstanceInfo>>>(); 存储,在服务注册信息的存储过程中,会处理几个重要逻辑:

  1. 然后遍历集群节点,发送当前注册信息进行集群间数据的同步。
  2. 在服务提供者和注册中心之间,会建立一个心跳检测机制,用于监控服务提供者的健康状态。
  3. 刷新触发 Eureka 自我保护机制的值。
  4. 更新 Eureka 读写缓存的数据,保证客户端获取数据的时候,从 ConcurrentHashMap<String, Map<String, Lease<InstanceInfo>>> registry 中获取最新的数据。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值