Eureka源码深度刨析-(6)EurekaServer多级缓存过期机制

“不积跬步,无以至千里。”

这篇文章内容比较短,可以开篇聊点题外话。

前几天,跟朋友闲聊,谈起了国内的互联网局势,“开始内卷”,其实内卷倒不是什么坏事,这不也恰恰说明国内的IT界“上限”在提高嘛,整体有了增长的态势,这是幸事。但是作为一个普通的码农,学习肯定是要的,我也鼓励大家利用业务时间充充电,我就是这么做的,这是我的第一层观点,即“学习不能停”。

至于怎么学习,这个得自己摸索,不过我个人的这些年的经验,可以简单跟大家分享分享,我早些年学技术,比较喜欢学习“新”技术,出了个什么新玩意,马上火急火燎的去写写demo,调调api,然后觉得自我感觉良好,啥都会用,常常浅尝辄止,并不深入。不深入是慢病,就像感染的潜伏期,跟没事人一样,一样遇上一些稍微棘手的Case,常常就是只能依赖百度,内心确实很虚,这就是浅学习的危害,这是我的第二个观点,想要成为高手,一定不能浮于表面,像做学问一样,深耕。

比如学习一个技术,首先做到入门,官方文档大致看下,网上搜索一些入门博客,跟着写几个demo,对基本原理有一定了解,就算入门了。

当了解一个技术之后,接下来要做的事情,就是在自己的项目中实践,一定要实践,只有在项目实践中才能更好的思考这个技术怎么用、用在哪儿、什么场景用,并且在使用的过程中会不断了解部署架构,运行原理,核心机制以及优化方式,就做到对技术比较熟悉了。

当对几个技术有了比较多的实践经验了,可以开始准备阅读源码了,可以选择一些优秀的这个技术的源码相关的博客,或者解读源码的书籍,但是书籍的话作者的水平参次不齐,需要指路人推荐,当你熟练阅读技术的核心源代码,就可以做到精通这个技术了,以后生产上出了什么事故,你可以根据报错信息,很快分析并定位报错原因,不再只是会依赖于百度。

最后说一下,你熟练使用50门技术,不如你精通10门技术,技术贵精不贵多

ok,我们步入正题,这篇文章,来重点看看eureka server端的多级缓存机制的过期失效机制。

在server端,关于过期,其实有3中机制,分别是主动过期,被动过期和定时过期。

(1)主动过期

主动过期主要是针对RW缓存,有新的服务注册、下线、故障都会刷新RW缓存的Map

比如有一个新实例来注册,在注册逻辑最后会调用invalidateCache方法,这个方法就是去过期掉RW缓存的Map。

public void register(InstanceInfo registrant, int leaseDuration, boolean isReplication) {
    read.lock();
    try {
        Map<String, Lease<InstanceInfo>> gMap = registry.get(registrant.getAppName());
        //注册逻辑 ... ...
        invalidateCache(registrant.getAppName(), registrant.getVIPAddress(), registrant.getSecureVipAddress());
        logger.info("Registered instance {}/{} with status {} (replication={})",
                    registrant.getAppName(), registrant.getId(), registrant.getStatus(), isReplication);
    } finally {
        read.unlock();
    }
}
private void invalidateCache(String appName, @Nullable String vipAddress, @Nullable String secureVipAddress) {
    // invalidate cache
    responseCache.invalidate(appName, vipAddress, secureVipAddress);
}
public void invalidate(String appName, @Nullable String vipAddress, @Nullable String secureVipAddress) {
    for (Key.KeyType type : Key.KeyType.values()) {
        for (Version v : Version.values()) {
            invalidate(
                new Key(Key.EntityType.Application, appName, type, v, EurekaAccept.full),
                new Key(Key.EntityType.Application, appName, type, v, EurekaAccept.compact),
                new Key(Key.EntityType.Application, ALL_APPS, type, v, EurekaAccept.full),
                new Key(Key.EntityType.Application, ALL_APPS, type, v, EurekaAccept.compact),
                new Key(Key.EntityType.Application, ALL_APPS_DELTA, type, v, EurekaAccept.full),
                new Key(Key.EntityType.Application, ALL_APPS_DELTA, type, v, EurekaAccept.compact)
            );
            if (null != vipAddress) {
                invalidate(new Key(Key.EntityType.VIP, vipAddress, type, v, EurekaAccept.full));
            }
            if (null != secureVipAddress) {
                invalidate(new Key(Key.EntityType.SVIP, secureVipAddress, type, v, EurekaAccept.full));
            }
        }
    }
}

在这里会调用readWriteCacheMap.invalidate(key)来过期RW缓存Map的数据,服务下线、故障都会走类似的逻辑,这里就不赘述了。

public void invalidate(Key... keys) {
    for (Key key : keys) {
        logger.debug("Invalidating the response cache key : {} {} {} {}, {}",
                     key.getEntityType(), key.getName(), key.getVersion(), key.getType(), key.getEurekaAccept());

        readWriteCacheMap.invalidate(key);
        Collection<Key> keysWithRegions = regionSpecificKeys.get(key);
        if (null != keysWithRegions && !keysWithRegions.isEmpty()) {
            for (Key keysWithRegion : keysWithRegions) {
                logger.debug("Invalidating the response cache key : {} {} {} {} {}",
                             key.getEntityType(), key.getName(), key.getVersion(), key.getType(), key.getEurekaAccept());
                readWriteCacheMap.invalidate(keysWithRegion);
            }
        }
    }
}

(2)被动过期

被动过期,主要是针对RO缓存,readOnlyCacheMap默认是每隔30秒,执行一个定时调度的线程任务,TimerTask,对readOnlyCacheMapreadWriteCacheMap中的数据进行一个比对,如果两块数据不一致的,那么就将readWriteCacheMap中的数据放到readOnlyCacheMap中来。

比如说readWriteCacheMap中,ALL_APPS这个key对应的缓存没了,那么最多30秒过后,就会同步到readOnelyCacheMap中去。

这段代码依然在ResponseCacheImpl的构造方法里,这个timer叫做一个eureka缓存填充的timer。

private final java.util.Timer timer = new java.util.Timer("Eureka-CacheFillTimer", true);

if (shouldUseReadOnlyResponseCache) {
    timer.schedule(getCacheUpdateTask(),
                   new Date(((System.currentTimeMillis() / responseCacheUpdateIntervalMs) * responseCacheUpdateIntervalMs)
                            + responseCacheUpdateIntervalMs),
                   responseCacheUpdateIntervalMs);
}

可以看到它的getCacheUpdateTask()方法直接返回一个TimerTask,就是完成RW缓存和RO缓存数据交互的逻辑。

private TimerTask getCacheUpdateTask() {
    return new TimerTask() {
        @Override
        public void run() {
            logger.debug("Updating the client cache from response cache");
            for (Key key : readOnlyCacheMap.keySet()) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Updating the client cache from response cache for key : {} {} {} {}",
                                 key.getEntityType(), key.getName(), key.getVersion(), key.getType());
                }
                try {
                    CurrentRequestVersion.set(key.getVersion());
                    Value cacheValue = readWriteCacheMap.get(key);
                    Value currentCacheValue = readOnlyCacheMap.get(key);
                    //如果RO缓存中的数据和RW不一致,则put
                    if (cacheValue != currentCacheValue) {
                        readOnlyCacheMap.put(key, cacheValue);
                    }
                } catch (Throwable th) {
                    logger.error("Error while updating the client cache from response cache for key {}", key.toStringCompact(), th);
                } finally {
                    CurrentRequestVersion.remove();
                }
            }
        }
    };
}

而这个responseCacheUpdateIntervalMs,默认30s。

@Override
public long getResponseCacheUpdateIntervalMs() {
    return configInstance.getIntProperty(
        namespace + "responseCacheUpdateIntervalMs", (30 * 1000)).get();
}

(3)定时过期

这个定时过期,实际上也是针对RW缓存的那个readWriteCacheMap的,在构建的时候会指定一个自动过期的时间,默认是180s,因此放入RW缓存中的数据默认会在3分钟之内过期掉。

this.readWriteCacheMap =
    CacheBuilder.newBuilder().initialCapacity(serverConfig.getInitialCapacityOfResponseCache())
    .expireAfterWrite(serverConfig.getResponseCacheAutoExpirationInSeconds(), TimeUnit.SECONDS)
    .removalListener(new RemovalListener<Key, Value>() {
        @Override
        public void onRemoval(RemovalNotification<Key, Value> notification) {
            Key removedKey = notification.getKey();
            ... ...

通过源码可以明确,这个getResponseCacheAutoExpirationInSeconds()的默认值就是180s。

@Override
public long getResponseCacheAutoExpirationInSeconds() {
    return configInstance.getIntProperty(
        namespace + "responseCacheAutoExpirationInSeconds", 180).get();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值