当项目启动时(eureka 的客户端),就会向 eureka-server 发送自己的元数据(原始数据)(运行的 ip,端口 port,健康的状态监控等,因为使用的是 http/ResuFul 请求风格),eureka-server 会在自己内部保留这些元数据(内存中)。(有一个服务列表)(restful 风
格,以 http 动词的请求方式,完成对 url 资源的操作)
项目启动成功了,除了向 eureka-server 注册自己成功,还会定时的向 eureka-server 汇报自己,心跳,表示自己还活着。(修改一个时间)
当项目关闭时,会给 eureka-server 报告,说明自己要下机了。
当项目超过了指定时间没有向 eureka-server 汇报自己,那么 eureka-server 就会认为此节点死掉了,会把它剔除掉,也不会放流量和请求到此节点了。
为什么要学源码? 答:了解他的原理 出了问题排查 bug,优化你的代码
Eureka-server 对外提供的是 restful 风格的服务以 http 动词的形式对 url 资源进行操作 get post put delete
http 服务 + 特定的请求方式 + 特定的 url 地址
只要利用这些 restful 我们就能对项目实现注册和发现,只不过,eureka 已经帮我们使用 java 语言写了 client,让我们的项目只要依赖 client 就能实现注册和发现!
只要你会发起 Http 请求,那你就有可能自己实现服务的注册和发现。不管你是什么语言!
总结:
当 eureka 启动的时候,会向我们指定的 serviceUrl 发送请求,把自己节点的数据以 post
请求的方式,数据以 json 形式发送过去。 当返回的状态码为 204 的时候,表示注册成功。
sources.ApplicationResource
public void register(InstanceInfo registrant, int leaseDuration, boolean isReplication) {try {read.lock();//通过服务名称得到注册的实例Map<String, Lease<InstanceInfo>> gMap = (AppName());REGISTER.increment(isReplication);//因为之前没有实例,肯定为 nullif (gMap == null) {//新建一个集合来存放实例final ConcurrentHashMap<String, Lease<InstanceInfo>> gNewMap = newConcurrentHashMap<String, Lease<InstanceInfo>>();gMap = registry.AppName(), gNewMap);if (gMap == null) {gMap = gNewMap;}
}//gMap 就是该服务的实例Lease<InstanceInfo> existingLease = (Id());
// Retain the last dirty timestamp without overwriting it, if there is already a lease
if (existingLease != null && (Holder() != null)) {Long existingLastDirtyTimestamp Holder().getLastDirtyTimestamp();Long registrationLastDirtyTimestamp = LastDirtyTimestamp();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 = Holder();
}
} else {
// The lease does not exist and hence it is a new registration
synchronized (lock) {
if (pectedNumberOfClientsSendingRenews > 0) {
// Since the client wants to register it, increase the number of clients
sending renews
pectedNumberOfClientsSendingRenews =
pectedNumberOfClientsSendingRenews + 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.ServiceUpTimestamp());
}//放到注册 map 的列表里gMap.Id(), lease);recentRegisteredQueue.add(new Pair<Long, String>(
System.currentTimeMillis(),
AppName() + "(" + Id() + ")"));
// This is where the initial state transfer of overridden status happens
if (!InstanceStatus.UNKNOWN.OverriddenStatus())) {
logger.debug("Found overridden status {} for instance {}. Checking to see if needs
to be add to the "
+ "overrides", OverriddenStatus(),
Id());
if (!Id())) {
logger.info("Not found overridden id {} and hence adding it",
Id());
overriddenInstanceStatusMap.Id(),
OverriddenStatus());
}
}
InstanceStatus overriddenStatusFromMap =
(Id());
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
if (InstanceStatus.UP.Status())) {
lease.serviceUp();
}
registrant.setActionType(ActionType.ADDED);
recentlyChangedQueue.add(new RecentlyChangedItem(lease));//设置心跳时间等参数registrant.setLastUpdatedTimestamp();
AppName(),
SecureVipAddress());
logger.info("Registered instance {}/{} with status {} (replication={})",
AppName(), Id(), Status(),
isReplication);
} finally {
read.unlock();
}
}
重要的类:
DiscoveryClient 里面的 register()方法完后注册的总体构造
AbstractJerseyEurekaHttpClient 里面的 register()方法具体发送注册请求(post)
InstanceRegistry 里面 register()方法接受客户端的注册请求
PeerAwareInstanceRegistryImpl 里面调用父类的 register()方法实现注册
AbstractInstanceRegistry 里面的 register()方法完成具体的注册保留数据到 map 集合
保存服务实例数据的集合:
第一个 key 是应用名称(全大写) spring.application.name
Value 中的 key 是应用的实例 id eureka.instance.instance-id
Value 中的 value 是 具体的服务节点信息
private final ConcurrentHashMap<String, Map<String,Lease<InstanceInfo>>> registry= new ConcurrentHashMap<String, Map<String,Lease<InstanceInfo>>>();
DiscoveryClient 的 renew()方法
续约的本质就是修改了服务节点的最后更新时间
duration:代表注册中心最长的忍耐时间:
并不是 30s 没有续约就里面剔除,而是 30 +duration(默认是 90s) 期间内没有续约,才剔除服务
Volatile 标识的变量是具有可见性的,当一条线程修改了我的剔除时间,其他线程就可以立马看到(应用场景:一写多读),后面在剔除里面有一个定时任务,去检查超时从而判断某一个服务是否应该被剔除。
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 :
Set()) {
Map<String, Lease<InstanceInfo>> leaseMap = Value();
if (leaseMap != null) {
//循环for (Entry<String, Lease<InstanceInfo>> leaseEntry :
Set()) {
Lease<InstanceInfo> lease = Value();
//判断过期,加入集合中if (lease.isExpired(additionalLeaseMs) && Holder() != null)
{expiredLeases.add(lease);}
}
}
}
// 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();
int registrySizeThreshold = (int) (registrySize *
RenewalPercentThreshold());
int evictionLimit = registrySize - registrySizeThreshold;
int toEvict = Math.min(expiredLeases.size(), evictionLimit);
if (toEvict > 0) {
logger.info("Evicting {} items (expired={}, evictionLimit={})", toEvict,
expiredLeases.size(), evictionLimit);
Random random = new Random(System.currentTimeMillis());
for (int i = 0; i < toEvict; i++) {
// Pick a random item (Knuth shuffle algorithm)
int next = i + Int(expiredLeases.size() - i);
Collections.swap(expiredLeases, i, next);
Lease<InstanceInfo> lease = (i);
String appName = Holder().getAppName();
String id = Holder().getId();
EXPIRED.increment();
logger.warn("DS: Registry: expired lease for {}/{}", appName, id);
//这整个方法并没有真的杀死过期的服务节点//下面这个方法才是真正干掉过期的服务internalCancel(appName, id, false);}
}
}
怎么删除一个集合里面过期的数据?
Redis 怎么清除过期的 key LRU(热点 key)
1 定时(k-thread)
2 惰性 (在再次访问该 key 时有作用)
3 定期 (使用一个线程来完成清除任务)
定期(实时性差) + 惰性
查看 evict()方法在哪里调用的
具体查看多久执行一次呢?
发现默认是 60s 执行一次
当然我们也可以自定义检测定时器的执行时间
本文发布于:2024-01-31 01:18:47,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170663512824308.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |