Guava本地缓存getAll方法

最近一个项目大量使用了guava的本地缓存服务。使用方式是对第三方数据接口返回的结果做本地缓存。

当时太年轻了,为了降低首次加载时对于第三方服务的QPS,使用了本地缓存的getAll方法,并提供了loadAll的重载实现。loadall方法中使用批量接口来获取第三方接口返回的数据。

那么问题来了,我们来看看官方对于getAll方法的注释:

 /**
   * Returns a map of the values associated with {@code keys}, creating or retrieving those values
   * if necessary. The returned map contains entries that were already cached, combined with newly
   * loaded entries; it will never contain null keys or values.
   *
   * <p>Caches loaded by a {@link CacheLoader} will issue a single request to
   * {@link CacheLoader#loadAll} for all keys which are not already present in the cache. All
   * entries returned by {@link CacheLoader#loadAll} will be stored in the cache, over-writing
   * any previously cached values. This method will throw an exception if
   * {@link CacheLoader#loadAll} returns {@code null}, returns a map containing null keys or values,
   * or fails to return an entry for each requested key.
   *
   * <p>Note that duplicate elements in {@code keys}, as determined by {@link Object#equals}, will
   * be ignored.
   *
   * @throws ExecutionException if a checked exception was thrown while loading the value. ({@code
   *     ExecutionException} is thrown <a
   *     href="https://github.com/google/guava/wiki/CachesExplained#interruption">even if
   *     computation was interrupted by an {@code InterruptedException}</a>.)
   * @throws UncheckedExecutionException if an unchecked exception was thrown while loading the
   *     values
   * @throws ExecutionError if an error was thrown while loading the values
   * @since 11.0
   */

其他都没啥问题。最大的问题是这句话:This method will throw an exception if loadAll returns {@code null}, returns a map containing null keys or values.

如果loadAll方法返回null,或者map中含有null的key或value,会抛异常!!!这会导致getAll方法调用失败。在高可用的要求下,这是绝对不被允许的。

来看一下getAll的源代码:

ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException {
    int hits = 0;
    int misses = 0;

    Map<K, V> result = Maps.newLinkedHashMap();
    Set<K> keysToLoad = Sets.newLinkedHashSet();

    //遍历key
    for (K key : keys) {
      //get一把先
      V value = get(key);
      //如果在result里面不包含key(去重)
      if (!result.containsKey(key)) {
        //result里面塞入key-value
        result.put(key, value);
        //如果value不存在
        if (value == null) {
          //遗失的数量++
          misses++;
          //等待load的key++
          keysToLoad.add(key);
        } else {
          //命中的数量++
          hits++;
        }
      }
    }

    try {
      if (!keysToLoad.isEmpty()) {
        try {
          //调用loadall方法载入数据
          Map<K, V> newEntries = loadAll(keysToLoad, defaultLoader);
          //遍历一遍
          for (K key : keysToLoad) {
            V value = newEntries.get(key);
            //拿不到抛异常InvalidCacheLoadException
            if (value == null) {
              throw new InvalidCacheLoadException("loadAll failed to return a value for " + key);
            }
            //塞入返回结果
            result.put(key, value);
          }
        } catch (UnsupportedLoadingOperationException e) {
          //如果loadall方法未覆盖,全部调用get方法
          for (K key : keysToLoad) {
            misses--; // get will count this miss
            result.put(key, get(key, defaultLoader));
          }
        }
      }
      return ImmutableMap.copyOf(result);
    } finally {
      globalStatsCounter.recordHits(hits);
      globalStatsCounter.recordMisses(misses);
    }
  }

getAll会先调用get方法获取数据,对于get不到的数据(未加载或过期),才会调用loadAll方法。如果loadAll方法中含有空的值,向上抛出异常。如果loadAll没有被重载,会继续调用get方法获取剩余的值。

所以结论是,如果项目中使用了getAll方法,但是又不希望被loadAll抛出异常,那么干掉loadAll的重载实现就好了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,765评论 18 399
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,284评论 25 708
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,923评论 18 139
  • 一. Java基础部分.................................................
    wy_sure阅读 3,835评论 0 11
  • 嗨,你还好吗? 去年刚入冬,便给自己许下心愿想去峨眉看雪、想去看腊梅盛开,最终还是错过了最想看的风景。近日成都的花...
    雷雨尘阅读 459评论 0 1