本文主要基于 Eureka 1.8.X 版本
1. 概述
2. 为什么需要过期
3. EvictionTask
4. 过期逻辑
RocketMQ / MyCAT / Sharding-JDBC 所有源码分析文章列表
RocketMQ / MyCAT / Sharding-JDBC 中文注释源码 GitHub 地址
您对于源码的疑问每条留言都将得到认真回复甚至不知道如何读源码也可以请教噢
新的源码解析文章实时收到通知每周更新一篇左右
认真的源码交流微信群
1. 概述
本文主要分享 Eureka-Server 过期超时续租的租约
FROM 深度剖析服务发现组件 Netflix Eureka
推荐 Spring Cloud 书籍:
请支持正版下载盗版, 等于主动编写低级 BUG
程序猿 DD Spring Cloud 微服务实战
周立 Spring Cloud 与 Docker 微服务架构实战
两书齐买, 京东包邮
推荐 Spring Cloud 视频:
Java 微服务实践 - Spring Boot
Java 微服务实践 - Spring Cloud
Java 微服务实践 - Spring Boot / Spring Cloud
2. 为什么需要过期
正常情况下, 应用实例下线时候会主动向 Eureka-Server 发起下线请求但实际情况下, 应用实例可能异常崩溃, 又或者是网络异常等原因, 导致下线请求无法被成功提交
介于这种情况, 通过 Eureka-Client 心跳延长租约, 配合 Eureka-Server 清理超时的租约解决上述异常
- 3. EvictionTask
- com.netflix.eureka.registry.AbstractInstanceRegistry.EvictionTask
, 清理租约过期任务在 Eureka-Server 启动时, 初始化 EvictionTask 定时执行, 实现代码如下:
- // AbstractInstanceRegistry.java
- /**
- * 清理租约过期任务
- */
- private final AtomicReference evictionTaskRef = new AtomicReference();
- protected void postInit() {
- // .... 省略无关代码
- // 初始化 清理租约过期任务
- if (evictionTaskRef.get() != null) {
- evictionTaskRef.get().cancel();
- }
- evictionTaskRef.set(new EvictionTask());
- evictionTimer.schedule(evictionTaskRef.get(),
- serverConfig.getEvictionIntervalTimerInMs(),
- serverConfig.getEvictionIntervalTimerInMs());
- }
配置
eureka.evictionIntervalTimerInMs
, 清理租约过期任务执行频率, 单位: 毫秒默认, 60000 毫秒
EvictionTask 实现代码如下:
- class EvictionTask extends TimerTask {
- @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);
- }
- }
- }
调用
#compensationTimeMs()
方法, 获得补偿时间毫秒数计算公式 = 当前时间 - 最后任务执行时间 - 任务执行频率为什么需要补偿时间毫秒数, 在 4. 过期逻辑
Lease#isisExpired(additionalLeaseMs)
方法 揭晓
#compensationTimeMs()
实现代码如下:
- /**
- * 最后任务执行时间
- */
- private final AtomicLong lastExecutionNanosRef = new AtomicLong(0L);
- long getCompensationTimeMs() {
- long currNanos = getCurrentTimeNano();
- long lastNanos = lastExecutionNanosRef.getAndSet(currNanos);
- if (lastNanos == 0L) {
- return 0L;
- }
- long elapsedMs = TimeUnit.NANOSECONDS.toMillis(currNanos - lastNanos);
- long compensationTime = elapsedMs - serverConfig.getEvictionIntervalTimerInMs();
- return compensationTime <= 0L ? 0L : compensationTime;
- }
由于 JVM GC , 又或是时间偏移( clock skew ) 等原因, 定时器执行实际比预期会略有延迟笔者在本机低负载运行, 大概 10 ms 内
compute a compensation time defined as the actual time this task was executed since the prev iteration, vs the configured amount of time for execution. This is useful for cases where changes in time (due to clock skew or gc for example) causes the actual eviction task to execute later than the desired time according to the configured cycle.
调用
#evict(compensationTime)
方法, 执行清理过期租约逻辑, 在 4. 过期逻辑 详细解析
4. 过期逻辑
调用
#evict(compensationTime)
方法, 执行清理过期租约逻辑, 实现代码如下:
- 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> expiredLeases = new ArrayList<>();
- for (Entry>> groupEntry : registry.entrySet()) {
- Map> leaseMap = groupEntry.getValue();
- if (leaseMap != null) {
- for (Entry> leaseEntry : leaseMap.entrySet()) {
- Lease lease = leaseEntry.getValue();
- if (lease.isExpired(additionalLeaseMs) && lease.getHolder() != 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 * serverConfig.getRenewalPercentThreshold());
- 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 + random.nextInt(expiredLeases.size() - i);
- Collections.swap(expiredLeases, i, next);
- Lease lease = expiredLeases.get(i);
- String appName = lease.getHolder().getAppName();
- String id = lease.getHolder().getId();
- EXPIRED.increment();
- logger.warn("DS: Registry: expired lease for {}/{}", appName, id);
- internalCancel(appName, id, false);
- }
- }
- }
第 3 至 7 行 : 判断允许执行清理过期租约逻辑, 主要和自我保护机制有关, 在 Eureka 源码解析 应用实例注册发现 (四) 之自我保护机制 有详细解析
第 9 至 24 行 : 获得所有过期的租约集合
第 19 行 : 调用
Lease#isisExpired(additionalLeaseMs)
方法, 判断租约是否过期, 实现代码如下:
- // Lease.java
- public boolean isExpired(long additionalLeaseMs) {
- return (evictionTimestamp> 0 || System.currentTimeMillis()> (lastUpdateTimestamp + duration + additionalLeaseMs));
- }
- public void renew() {
- lastUpdateTimestamp = System.currentTimeMillis() + duration;
- }
注意: 在不考虑 additionalLeaseMs 参数的情况下, 租约过期时间比预期多了一个 duration, 原因在于 #renew() 方法错误的设置
lastUpdateTimestamp = System.currentTimeMillis() + duration
, 正确的设置应该是
- lastUpdateTimestamp = System.currentTimeMillis()
- 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.
- TODO[0023]:additionalLeaseMs
第 26 至 34 行 : 计算最大允许清理租约的数量, 后计算允许清理租约的数量
注意: 即使 Eureka-Server 关闭自我保护机制, 如果使用
renewalPercentThreshold = 0.85
默认配置, 结果会是分批逐步过期举个例子:
- // 假设 20 个租约, 其中有 10 个租约过期
- // 第一轮执行开始
- int registrySize = 20;
- int registrySizeThreshold = (int)(20 * 0.85) = 17;
- int evictionLimit = 20 - 17 = 3;
- int toEvict = Math.min(10, 3) = 3;
- // 第一轮执行结束, 剩余 17 个租约, 其中有 7 个租约过期
- // 第二轮执行开始
- int registrySize = 17;
- int registrySizeThreshold = (int)(17 * 0.85) = 14;
- int evictionLimit = 17 - 14 = 3;
- int toEvict = Math.min(7, 3) = 3;
- // 第二轮执行结束, 剩余 14 个租约, 其中有 4 个租约过期
- // 第三轮执行开始
- int registrySize = 14;
- int registrySizeThreshold = (int)(14 * 0.85) = 11;
- int evictionLimit = 14 - 11 = 3;
- int toEvict = Math.min(4, 3) = 3;
- // 第三轮执行结束, 剩余 11 个租约, 其中有 1 个租约过期
- // 第四轮执行开始
- int registrySize = 11;
- int registrySizeThreshold = (int)(11 * 0.85) = 9;
- int evictionLimit = 11 - 9 = 2;
- int toEvict = Math.min(1, 2) = 1;
- // 第四轮执行结束, 剩余 10 个租约, 其中有 0 个租约过期结束
结论: 是否开启自我保护的差别, 在于是否执行清理过期租约逻辑如果想关闭分批逐步过期, 设置
renewalPercentThreshold = 0
由于 JVM GC , 或是本地时间差异原因, 可能自我保护机制的阀值
- expectedNumberOfRenewsPerMin
- numberOfRenewsPerMinThreshold
不够正确, 在过期这个相对危险的操作, 重新计算自我保护的阀值
第 35 至 51 行 : 随机清理过期的租约由于租约是按照应用顺序添加到数组, 通过随机的方式, 尽量避免单个应用被全部过期
第 39 行 : 传入当前时间为种子生成随机, 避免 Java 的伪随机情况在 为什么说 Java 中的随机数都是伪随机数? 有详细解析
第 41 至 43 行 : 随机调换后面的元素到当前位置( i )
第 50 行 : 调用 #internalCancel() 方法, 下线已过期的租约, 在 Eureka 源码解析 应用实例注册发现 (四) 之自我保护机制 3.2 下线应用实例信息 有详细解析
来源: http://www.suo.im/4y3hXZ