上篇博客《SpringCloud——Eureka服务注册和发现》介绍了Eureka的基本功能,这篇我们来聊聊eureka是如何实现的。

上图是eureka的架构图,Eureka分为Server和client,图中,蓝色为Server端,绿色为client。

基本流程:

1、最左边的client(即服务提供者)发起us-east-1c注册请求;

2、之后,Eureka
Server集群中的其他两个node(us-east-1d和us-east-1e进行Replicate复制);

3、图下放的两个client(即服务消费者)分别向三个server获取注册信息及Get
Registry。

注册过程:

Eureka Client:

1、DiscoveryClient中的initScheduledTasks()以定时任务的方式执行。

private void initScheduledTasks() {
instanceInfoReplicator = new InstanceInfoReplicator(
this,
instanceInfo,
clientConfig.getInstanceInfoReplicationIntervalSeconds(),
2); // burstSize
instanceInfoReplicator.start(clientConfig.getInitialInstanceInfoReplicationIntervalSeconds());
}

2、在InstanceInfoReplicator的run方法中,调用discoveryClient的注册方法。

	public void run() {
try {
discoveryClient.refreshInstanceInfo(); Long dirtyTimestamp = instanceInfo.isDirtyWithTime();
if (dirtyTimestamp != null) {
discoveryClient.register();
instanceInfo.unsetIsDirty(dirtyTimestamp);
}
} catch (Throwable t) {
logger.warn("There was a problem with the instance info replicator", t);
} finally {
Future next = scheduler.schedule(this, replicationIntervalSeconds, TimeUnit.SECONDS);
scheduledPeriodicRef.set(next);
}
}

3、DiscoveryClient,使用rest调用。

boolean register() throws Throwable {	        logger.info(PREFIX + appPathIdentifier + ": registering service...");
EurekaHttpResponse<Void> httpResponse;
try {
httpResponse = eurekaTransport.registrationClient.register(instanceInfo);
} catch (Exception e) {
logger.warn("{} - registration failed {}", PREFIX + appPathIdentifier, e.getMessage(), e);
throw e;
}
if (logger.isInfoEnabled()) {
logger.info("{} - registration status: {}", PREFIX + appPathIdentifier, httpResponse.getStatusCode());
}
return httpResponse.getStatusCode() == 204;
}

Eureka Server:

1、rest接口,即服务端rest方式调用的接口。

 @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.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());
}
}
} registry.register(info, "true".equals(isReplication));
return Response.status(204).build(); // 204 to be backwards compatible
}

2、在PeerAwareInstanceRegistryImpl中的register方法

    @Override
public void register(final InstanceInfo info, final boolean isReplication) {
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);
}

注册方法中,租约不存在。具体如下

if (existingLease != null && (existingLease.getHolder() != null)) {
//续租
.......
}else{
// The lease does not exist and hence it is a new registration
synchronized (lock) {
if (this.expectedNumberOfRenewsPerMin > 0) {
// Since the client wants to cancel it, reduce the threshold
// (1
// for 30 seconds, 2 for a minute)
this.expectedNumberOfRenewsPerMin = this.expectedNumberOfRenewsPerMin + 2;
this.numberOfRenewsPerMinThreshold =
(int) (this.expectedNumberOfRenewsPerMin * serverConfig.getRenewalPercentThreshold());
}
}
logger.debug("No previous lease information found; it is new registration");
}

构造注册信息,处理缓存信息。

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

Eureka服务注册过程的更多相关文章

  1. Eureka服务注册过程详解之IpAddress(详解eureka.instance.prefer-ip-address = true 与 eureka.instance.prefer-ip-address)

    分析,eureka.instance.prefer-ip-address 本节解释为什么配置eureka.instance.prefer-ip-address = true时,注册到Eureka Se ...

  2. 【SpringCloud Eureka源码】从Eureka Client发起注册请求到Eureka Server处理的整个服务注册过程(下)

    目录 一.Spring Cloud Eureka Server自动配置及初始化 @EnableEurekaServer EurekaServerAutoConfiguration - 注册服务自动配置 ...

  3. SpringCloud学习--Eureka 服务注册与发现

    目录 一:构建项目 二:服务注册与发现 为什么选择Eureka,请看上一篇博客 Eureka -- 浅谈Eureka 项目构建 IDEA 选择 New Project 选择 Spring Initia ...

  4. Spring-cloud & Netflix 源码解析:Eureka 服务注册发现接口 ****

    http://www.idouba.net/spring-cloud-source-eureka-client-api/?utm_source=tuicool&utm_medium=refer ...

  5. springcloud(第三篇)springcloud eureka 服务注册与发现 *****

    http://blog.csdn.net/liaokailin/article/details/51314001 ******************************************* ...

  6. 搭建eureka服务

    1.pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www ...

  7. Spring Cloud官方文档中文版-服务发现:Eureka服务端

    官方文档地址为:http://cloud.spring.io/spring-cloud-static/Dalston.SR3/#spring-cloud-eureka-server 文中例子我做了一些 ...

  8. 1 Spring Cloud Eureka服务治理

    注:此随笔为读书笔记.<Spring Cloud微服务实战> 什么是微服务? 微服务是将一个原本独立的系统拆分成若干个小型服务(一般按照功能模块拆分),这些小型服务都在各自独立的进程中运行 ...

  9. 笔记:Spring Cloud Eureka 服务发现与消费

    服务发现与消费,其服务发现的任务是由Eureka的客户端完成,而服务的消费任务由Ribbon.JerseyClient等完成,Ribbon是一个基于HTTP和TCP的客户端负载均衡器:使用Jersey ...

随机推荐

  1. 核密度估计 Kernel Density Estimation (KDE) MATLAB

    对于已经得到的样本集,核密度估计是一种可以求得样本的分布的概率密度函数的方法: 通过选取核函数和合适的带宽,可以得到样本的distribution probability,在这里核函数选取标准正态分布 ...

  2. 自己写的一些Excel及WordVBA函数[原创]

    1.将Excel当前工作表另存至桌面 Excel中有时一个工作簿中工作表特别多,需要快速单独存取其中一个,可用以下代码快速存至桌面 Sub 另存工作表到桌面() Dim sh As Worksheet ...

  3. SAP SM13 V2更新队列批量执行

    SE38输入程序名RSM13005 Function Module 输入MCEX_UPDATE_03 Client 输入800 其他默认 执行

  4. 20155213 实验三《敏捷开发与XP实践》实验报告

    20155213 实验三<敏捷开发与XP实践>实验报告 实验内容 XP基础 XP核心实践 相关工具 实验要求 1.没有Linux基础的同学建议先学习<Linux基础入门(新版)> ...

  5. 20155213 2016-2017-2 《Java程序设计》第一周学习总结

    20155213 2016-2017-2 <Java程序设计>第一周学习总结 教材学习内容总结 了解JVM.JRE与JDK,并下载.安装.测试JDK JVM JVM是Java Virtua ...

  6. 实验一 Java开发环境的熟悉(Linux+Eclipse)

    实验一 Java开发环境的熟悉(Linux+Eclipse) 在Linux或Window或macOS中命令行下运行Java 在Linux 或Window或 macOS环境中 IDEA中调试设置断点 实 ...

  7. dsu on tree总结

    dsu on tree 树上启发式合并.我并不知道为什么要叫做这个名字... 干什么的 可以在\(O(n\log n)\)的时间内完成对子树信息的询问,可横向对比把树按\(dfs\)序转成序列问题的\ ...

  8. 优步uber司机常见问题与答案(成都地区官方)

    成都地区优步司机常见问题,官方内容,有点多,常出现的问题都收录在这里了,大家可以看看.(注:文章转自官方,非原创) 以下为成都优步合作车主最常见的问题列表和答案.对于绝大多数的车主端问题,您都可以在下 ...

  9. 【LG3206】[HNOI2010]城市建设

    [LG3206][HNOI2010]城市建设 题面 洛谷 题解 有一种又好想.码得又舒服的做法叫线段树分治+\(LCT\) 但是因为常数过大,无法跑过此题. 所以这里主要介绍另外一种玄学\(cdq\) ...

  10. 运行ntpdate报错:Temporary failure in name resolution

    一.问题报错: 忽然发现某台机器时间慢了些几分钟,之前没有搭建ntpd服务,目前都是使用的ntpdate加定时任务进行时间同步.直接执行ntpdate报错如下: # ntpdate cn.pool.n ...