guava cache

本文介绍了如何使用Guava Cache,包括通过 `.newBuilder()` 创建缓存对象,设置 `.maximumSize()` 缓存大小,`.expireAfterWrite()` 缓存失效时间,以及添加 `.removalListener()` 移除监听器。自定义`RemovalListener`可以在键被移除时进行操作,`.recordStats()` 用于记录缓存状态。Guava Cache内部基于类似`ConcurrentHashMap`的数据结构,并管理失效时间和状态信息,注意键值均不能为null。
Cache<String, Map<String, String>> cache = CacheBuilder.newBuilder().maximumSize(CACHR_MAX_SIZE)
            .expireAfterWrite(CACHE_EXPIRE_TIME, TimeUnit.HOURS)
             .removalListener() 
            .recordStats().build();

.newBuilder() //创建缓存对象

public static CacheBuilder<Object, Object> newBuilder() {
    return new CacheBuilder<Object, Object>();
  }

.maximumSize(CACHR_MAX_SIZE)//设置缓存大小
这里会有几个参数的校验,初始化时都是通过的,设置完之后如果再次设置则会抛异常

public CacheBuilder<K, V> maximumSize(long size) {
    checkState(this.maximumSize == UNSET_INT, "maximum size was already set to %s",
        this.maximumSize);
    checkState(this.maximumWeight == UNSET_INT, "maximum weight was already set to %s",
        this.maximumWeight);
    checkState(this.weigher == null, "maximum size can not be combined with weigher");
    checkArgument(size >= 0, "maximum size must not be negative");
    this.maximumSize = size;
    return this;
  }

.expireAfterWrite(CACHE_EXPIRE_TIME, TimeUnit.HOURS)//设置缓存失效时间
这里也会有校验,底层通过纳秒存储

public CacheBuilder<K, V> expireAfterWrite(long duration, TimeUnit unit) {
    checkState(expireAfterWriteNanos == UNSET_INT, "expireAfterWrite was already set to %s ns",
        expireAfterWriteNanos);
    checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
    this.expireAfterWriteNanos = unit.toNanos(duration);//时间转成纳秒
    return this;
  }

.removalListener() //移除监听,在key从缓存中remove时会调用
自定义实现RemovalListener中的onRemoval方法在key移除时会调用

public <K1 extends K, V1 extends V> CacheBuilder<K1, V1> removalListener(
      RemovalListener<? super K1, ? super V1> listener) {
    checkState(this.removalListener == null);

    // safely limiting the kinds of caches this can produce
    @SuppressWarnings("unchecked")
    CacheBuilder<K1, V1> me = (CacheBuilder<K1, V1>) this;
    me.removalListener = checkNotNull(listener);
    return me;
  }

.recordStats()//主要记录cache的状态,包括hit命中数量,miss数量,加载成功数量,加载异常数量,总加载时间,驱逐数量

public CacheBuilder<K, V> recordStats() {
    statsCounterSupplier = CACHE_STATS_COUNTER;
    return this;
  }
  static final Supplier<StatsCounter> CACHE_STATS_COUNTER =
      new Supplier<StatsCounter>() {
    @Override
    public StatsCounter get() {
      return new SimpleStatsCounter();
    }
public static final class SimpleStatsCounter implements StatsCounter {
    private final LongAddable hitCount = LongAddables.create();
    private final LongAddable missCount = LongAddables.create();
    private final LongAddable loadSuccessCount = LongAddables.create();
    private final LongAddable loadExceptionCount = LongAddables.create();
    private final LongAddable totalLoadTime = LongAddables.create();
    private final LongAddable evictionCount = LongAddables.create();
  };
  }

guava cache底层使用类似ConcurrentHashMap的实现,加上了失效时间、状态信息的管理。结构图如下
在这里插入图片描述

注意:cache的key和value不可以为null

在这里插入图片描述
在这里插入图片描述

### Guava 缓存的使用与实现 #### 创建和配置缓存实例 `LocalCache` 是整个 Guava Cache 的核心类,包含了数据结构以及基本操作方法[^1]。通过 `CacheBuilder` 类可以方便地构建并定制化缓存对象。 ```java import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; // 构建一个简单的本地缓存实例 Cache<String, String> cache = CacheBuilder.newBuilder() .maximumSize(100) // 设置最大条目数为100 .build(); ``` #### 自定义加载器 对于更复杂的场景,可以通过指定 `CacheLoader` 来自动填充缺失键对应的值: ```java import com.google.common.base.Optional; import com.google.common.cache.CacheLoader; Cache<String, Optional<String>> loadingCache = CacheBuilder.newBuilder() .maximumSize(100) .build(new CacheLoader<String, Optional<String>>() { @Override public Optional<String> load(String key) throws Exception { return Optional.ofNullable(fetchValueForKey(key)); } }); ``` 这里展示了如何设置当请求不存在于缓存中的时候,默认调用给定的方法来获取该值,并将其加入到缓存中以便后续访问[^2]。 #### 添加、检索及移除元素 可以直接利用 put 方法向缓存添加新项;getIfPresent 可用于查询特定键是否存在及其关联值;而 invalidate 则允许删除单个或全部记录。 ```java // 向缓存中添加一项 cache.put("key", "value"); // 获取已存在的项 String value = cache.getIfPresent("key"); // 移除某项 cache.invalidate("key"); ``` #### 高级特性支持 Guava 还提供了诸如过期时间(expireAfterWrite/expireAfterAccess)、刷新机制(refresh)等功能的支持,这些都极大地方便了开发者针对不同应用场景灵活调整缓存行为。 #### 并发控制优化 由于设计之初就考虑到了多线程环境下的高效运作,因此即使是在高并发读写的条件下也能保持良好的性能表现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值