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;
@NoArgsConstructor
@SuppressWarnings("all")
public class GuavaCacheUtils {
public static final int MAX = 20;
@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);
}
}