美文网首页
guava本地缓存getAll方法

guava本地缓存getAll方法

作者: 1angxi | 来源:发表于2016-07-13 10:43 被阅读1078次

最近一个项目大量使用了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的重载实现就好了。

相关文章

  • guava本地缓存getAll方法

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

  • guavaCache本地缓存失效方案expireAfterWri

    Guava实现本地缓存,为了保证缓存一致性,本地缓存需要被动的失效(即设置失效时间)。Guava Cache有两种...

  • Guava Cache实现原理浅析

    一.概述 在上篇文章《Guava Cache做本地缓存那些事》中我介绍了Guava Cache作为本地缓存的一般用...

  • Guava Cache

    原文 使用Guava cache构建本地缓存 - sameLuo的个人空间 - OSCHINA Guava Cac...

  • guava 本地缓存

    介绍 Guava cache是本地缓存的一种实现。 Guava Cache与ConcurrentMap很相似,但也...

  • 13 | Guava Cache 原理

    Guava Cache Guava Cache 是一种非常优秀的本地缓存解决方案,提供了基于容量,时间和索引的缓存...

  • springboot整合guava cache本地缓存

    guava cache 是本地缓存应用比较广的,支持定制化设置缓存,包括缓存数量、缓存时间,简单几步就可以完成本地...

  • 缓存设计

    目录 缓存设计需要考虑的地方 项目代码编写 mybaits缓存设计原理 guava缓存设计原理 本地缓存设计需要考...

  • 为什么是 Redis

    为什么要用 redis 而不用 map/guava 做缓存? 缓存分为本地缓存和分布式缓存。以 Java 为例,使...

  • Redis面试热点问题

    为什么要用 redis 而不用 map/guava 做缓存? 缓存分为本地缓存和分布式缓存。以 Java 为例,使...

网友评论

      本文标题:guava本地缓存getAll方法

      本文链接:https://www.haomeiwen.com/subject/euvsjttx.html