在 Guava 缓存库中,LoadingCache 和 Cache 是两个不同的接口,它们在功能和使用方式上有一些区别。
-
LoadingCache:LoadingCache是Cache接口的子接口,继承了Cache的所有方法,并添加了一些额外的方法。LoadingCache提供了自动加载缓存项的能力。当通过get方法获取缓存项时,如果缓存中不存在该项,LoadingCache会自动调用指定的加载器(CacheLoader)来加载该项,并将其放入缓存中。LoadingCache的get方法会抛出ExecutionException异常,因为加载缓存项的过程可能会发生异常。LoadingCache的getUnchecked方法是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);
-
Cache:Cache是 Guava 缓存库的基本接口,提供了基本的缓存功能。Cache的get方法用于获取缓存项,如果缓存中不存在该项,则返回null。Cache的put方法用于向缓存中添加或更新缓存项。Cache的invalidate方法用于从缓存中移除指定的缓存项。Cache的asMap方法返回一个ConcurrentMap,可以直接操作缓存中的数据。- 示例代码:
Cache<Key, Value> cache = CacheBuilder.newBuilder().build(); Value value = cache.getIfPresent(key); cache.put(key, value); cache.invalidate(key);
总结:
LoadingCache是Cache的子接口,提供了自动加载缓存项的能力。LoadingCache的get方法会抛出ExecutionException异常,而Cache的get方法返回null。LoadingCache的getUnchecked方法是get方法的非检查版本,不会抛出异常。Cache提供了基本的缓存功能,包括获取、添加、更新和移除缓存项的操作。