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.
   *
   * 

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. * *

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 even if * computation was interrupted by an {@code InterruptedException}.) * @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 getAll(Iterable keys) throws ExecutionException {
    int hits = 0;
    int misses = 0;

    Map result = Maps.newLinkedHashMap();
    Set 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 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的重载实现就好了。

你可能感兴趣的:(Guava本地缓存getAll方法)