Guava - 一个依托于 Guava cache 的工具类

Guava - 一个依托于 Guava cache 的工具类


1、代码

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @author Created by 谭健 on 2020/7/30. 星期四. 10:17.
 * © All Rights Reserved.
 */
@NoArgsConstructor
@SuppressWarnings("all")
public class GuavaCacheUtils {

  /**
   * 缓存中最大存储对象是数
   */
  public static final int MAX = 20;

  /**
   * 创建一个临时缓存块
   *
   * @param k        key
   * @param v        value
   * @param duration 过期时间
   * @param unit     时间单位
   * @param listener key 被移除的监听器
   */
  @SneakyThrows
  public static <K, V> Cache<K, V> buildTempCache(K k, V v, long duration, TimeUnit unit, RemovalListener<? super K, ? super V> listener) {
    CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    builder.maximumSize(MAX);
    Optional.ofNullable(listener).ifPresent(builder::removalListener);
    if (CommonUtils.isNotZeroLong(duration)) {
      builder.expireAfterWrite(duration, unit);
    }
    Cache<K, V> cache = builder.build();
    cache.put(k, v);
    return cache;
  }

  public static <K, V> Cache<K, V> buildTempCache(K k, V v, long duration, TimeUnit unit) {
    return buildTempCache(k, v, duration, unit, null);
  }

  public static <K, V> Cache<K, V> buildTempCache(K k, V v) {
    return buildTempCache(k, v, 1, TimeUnit.MINUTES, null);
  }


}

猜你喜欢

转载自blog.csdn.net/qq_15071263/article/details/107838140