Guava cache中 LoadingCache和Cache的区别

在 Guava 缓存库中,LoadingCacheCache 是两个不同的接口,它们在功能和使用方式上有一些区别。

  1. LoadingCache

    • LoadingCacheCache 接口的子接口,继承了 Cache 的所有方法,并添加了一些额外的方法。
    • LoadingCache 提供了自动加载缓存项的能力。当通过 get 方法获取缓存项时,如果缓存中不存在该项,LoadingCache 会自动调用指定的加载器(CacheLoader)来加载该项,并将其放入缓存中。
    • LoadingCacheget 方法会抛出 ExecutionException 异常,因为加载缓存项的过程可能会发生异常。
    • LoadingCachegetUnchecked 方法是 get 方法的非检查版本,不会抛出异常,但如果加载缓存项时发生异常,异常会被包装为 UncheckedExecutionException
    • 示例代码:
      LoadingCache<Key, Value> cache = CacheBuilder.newBuilder()
          .build(new CacheLoader<Key, Value>() {
              public Value load(Key key) throws AnyException {
                  // 加载缓存项的逻辑
              }
          });
      Value value = cache.get(key);
      
  2. Cache

    • Cache 是 Guava 缓存库的基本接口,提供了基本的缓存功能。
    • Cacheget 方法用于获取缓存项,如果缓存中不存在该项,则返回 null
    • Cacheput 方法用于向缓存中添加或更新缓存项。
    • Cacheinvalidate 方法用于从缓存中移除指定的缓存项。
    • CacheasMap 方法返回一个 ConcurrentMap,可以直接操作缓存中的数据。
    • 示例代码:
      Cache<Key, Value> cache = CacheBuilder.newBuilder()
          .build();
      Value value = cache.getIfPresent(key);
      cache.put(key, value);
      cache.invalidate(key);
      

总结:

  • LoadingCacheCache 的子接口,提供了自动加载缓存项的能力。
  • LoadingCacheget 方法会抛出 ExecutionException 异常,而 Cacheget 方法返回 null
  • LoadingCachegetUnchecked 方法是 get 方法的非检查版本,不会抛出异常。
  • Cache 提供了基本的缓存功能,包括获取、添加、更新和移除缓存项的操作。

你可能感兴趣的:(guava,java,开发语言)