1、缓存(Cache)-工具类
1、需引入插件依赖
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>16.0.1</version>
</dependency>
2、Demo:
@Slf4j
public class CacheUtil {
public static CacheUtil create() {
return new CacheUtil();
}
public static CacheUtil create(Long number, TimeUnit timeUnit) {
return new CacheUtil(number, timeUnit);
}
private Cache<String, Object> customCache;
/**
* 无参构造:缓存过期时间(指定对象被写入到缓存后多久过期),默认为1天.
* .recordStats(): 开启统计信息开关,统计缓存的命中率
*/
private CacheUtil() {
customCache = CacheBuilder.newBuilder()
.expireAfterWrite(1L, TimeUnit.HOURS)
.recordStats()
.removalListener(new RemovalListener<Object, Object>() {
@Override
public void onRemoval(RemovalNotification<Object, Object> notification) {
log.info(notification.getKey() + " was removed, cause is " + notification.getCause());
}
})
.build();
cleanCache();
}
/**
* 缓存过期时间(指定对象被写入到缓存后多久过期),为传入的单位
* .recordStats(): 开启统计信息开关,统计缓存的命中率
* @param timeUnit: 过期时间单位,秒分时日
*/
private CacheUtil(Long number, TimeUnit timeUnit) {
//如果传入过期时间数值为空,则默认为1
if(number == null){
number = 1L;
}
customCache = CacheBuilder.newBuilder()
.expireAfterWrite(number, timeUnit)
.recordStats()
.removalListener(new RemovalListener<Object, Object>() {
@Override
public void onRemoval(RemovalNotification<Object, Object> notification) {
log.info(notification.getKey() + " was removed, cause is " + notification.getCause());
}
})
.build();
cleanCache();
}
/**
* 清空缓存
*/
public void cleanCache() {
customCache.cleanUp();
}
public Object get(String key, Callable<Object> callable) throws ExecutionException {
return customCache.get(key, callable);
}
public Object get(String key) throws ExecutionException {
return customCache.getIfPresent(key);
}
public void put(String key, Object value) throws ExecutionException {
customCache.put(key, value);
}
public static void main(String[] args) throws ExecutionException {
CacheUtil cacheUtil = CacheUtil.create();
cacheUtil.put("test",1111);
Object test = cacheUtil.get("test");
System.out.println(test.toString());
cacheUtil.cleanCache();
System.out.println(cacheUtil.get("test"));
}
}