Guava 笔记二: cache简介

Guava 笔记二: cache简介

为什么要用cache

Cache是用来缓存哪些以后需要,并且得到这个值需要花费很多cost的对象。

Cache和ConcurrentMap很相像,最本质的区别是ConcurrentMap是强引用,只能显式的remove,Cache为了提高内存的利用率,可以持有weak value和weak reference。为什么是像是ConcurrentMap呢?因为cache实现了线程安全,多个线程访问同时写的时候,不会造成重复.

JDK cache?

Guava Cache使用场景
  • 需要以内存换取性能.
  • 需要使用多次缓存的值.
  • 缓存不超过系统的RAM。Guava只使用内存,不会使用文件或者其他的。如果你需要缓存到到服务器的其他地方,考虑一下Memcached.
怎么使用Cache
创建guava cache
  1. 从CacheLoader进行创建

    LoadingCache graphs = CacheBuilder.newBuilder()
       .maximumSize(1000)
       .build(
           new CacheLoader() {
             public Graph load(Key key) throws AnyException {
               return createExpensiveGraph(key);
             }
           });
    
    ...
    try {
     return graphs.get(key);
    } catch (ExecutionException e) {
     throw new OtherException(e.getCause());
    }
  2. From a Callable

    Cache cache = CacheBuilder.newBuilder()
    .maximumSize(1000)
    .build(); // look Ma, no CacheLoader
    ...
    try {
    // If the key wasn't in the "easy to compute" group, we need to
    // do things the hard way.
    cache.get(key, new Callable() {
    @Override
    public Value call() throws AnyException {
    return doThingsTheHardWay(key);
    }
    });
    } catch (ExecutionException e) {
    throw new OtherException(e.getCause());
    }

  1. get操作
    如果存在就get出来,否则就会新建一个key放到cache里
  2. Insert操作
    插入直接调用put操作就好
  3. Eviction
    1. 根据size进行限定
      CacheBuilder.maximumSize(long)
    2. 根据时间进行限定
      • expireAfterAccess(long, TimeUnit)
      • expireAfterWrite(long, TimeUnit)

其他特性:
1. 可以使用弱引用
* CacheBuilder.weakKeys()
* CacheBuilder.weakValues()
* CacheBuilder.softValues()
2. 手动移除(失效的)
通过调用方法
* 移除一个Cache.invalidate(key)
* 移除多个Cache.invalidateAll(keys)
* 移除全部Cache.invalidateAll()
3. Removal Listener 可以实现在key被移除的时候,做一些什么东西。
4. Statistics 可以通过CacheBuilder.recordStats()可以收集cache的统计资料。可以提供类似一下内容和更多内容:
* hitRate()
* averageLoadPenalty()
* evictionCount()
5. asMap返回一个ConcurrentMap的对象

Summary:
guava cache是一个类似提供cache的功能,但是是不太完备的功能,可能我们用的最多还是Ecache. 这里只是了解guava cache是什么,有什么作用.所以只能算简介.


  1. guava官方wiki
  2. 关于guava很好的理解

你可能感兴趣的:(JAVA,缓存,cache,guava)