http://www.majunwei.com/view/201808131007529750.html
深入理解Eureka - Eureka Server缓存机制
马军伟 Spring Cloud深入原理 1368 2018-08-13 / 2018-08-13
目录
为了提高Eureka Server注册中心的性能,Eureka Server提供了二级缓存机制,将服务注册信息保存在二级缓存中。
第一层缓存:readOnlyCacheMap,本质上是ConcurrentHashMap
第二层缓存:readWriteCacheMap,本质上是Guava缓存
缓存逻辑
Register、Cancel、Evict时都会清空二级缓存readWriteCacheMap。
- private void invalidateCache(String appName, @Nullable String vipAddress, @Nullable String secureVipAddress) {
- // invalidate cache
- responseCache.invalidate(appName, vipAddress, secureVipAddress);
- }
然后TimerTask定时(默认30S)将readWriteCacheMap同步到readOnlyCacheMap。
- if (shouldUseReadOnlyResponseCache) {
- timer.schedule(getCacheUpdateTask(),
- new Date(((System.currentTimeMillis() / responseCacheUpdateIntervalMs) * responseCacheUpdateIntervalMs)
- + responseCacheUpdateIntervalMs),
- responseCacheUpdateIntervalMs);
- }
缓存用途
Eureka Client获取注册列表时,首先判断是否开启了二级缓存,如果开启了则从readOnlyCacheMap中获取,否则从readWriteCacheMap中获取。
- /**
- * Get the payload in both compressed and uncompressed form.
- */
- @VisibleForTesting
- Value getValue(final Key key, boolean useReadOnlyCache) {
- Value payload = null;
- try {
- if (useReadOnlyCache) {
- final Value currentPayload = readOnlyCacheMap.get(key);
- if (currentPayload != null) {
- payload = currentPayload;
- } else {
- payload = readWriteCacheMap.get(key);
- readOnlyCacheMap.put(key, payload);
- }
- } else {
- payload = readWriteCacheMap.get(key);
- }
- } catch (Throwable t) {
- logger.error("Cannot get value for key : {}", key, t);
- }
- return payload;
- }
如何配置二级缓存
可通过eureka.server.shouldUseReadOnlyResponseCache配置决定是否开启二级缓存。默认是开启的(true)
待讨论问题
这里的二级缓存是通过TimerTask更新的(默认30S更新一次),也就是说在更新间隔内如果有register、cancel、evit操作,则一级缓存和二级缓存存在一定时间的不一致性,也就是获取到的不一定是最新的。如果对注册中心没有特别的性能需求,建议关闭。
Spring Cloud实战项目Jbone地址
github地址:https://github.com/417511458/jbone
码云地址:https://gitee.com/majunwei2017/jbone
原创文章,转载请注明出处:转载自小马过河 - 深入理解Eureka - Eureka Server缓存机制