您的位置:首页 > 其它

本地缓存实现之Guava Cache

2017-11-26 17:13 459 查看


示例代码

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;

/**
* 类说明:Guava缓存测试类
*
* @author ruipeng.lrp
* @since 2017/11/26
**/
public class GuavaCache {
public static Cache<String, String> caches = CacheBuilder.newBuilder().maximumSize(128)// 设置容量上限
.expireAfterAccess(3, TimeUnit.SECONDS) // 若3s内没有读写请求则进行回收
.removalListener(new RemovalListener<String, String>() {
// 移除监听器
@Override
public void onRemoval(RemovalNotification<String, String> notification) {
System.out.println(notification.getKey());
}

}).build();

public static String get(String key) throws Exception {
String rr = caches.get(key, new Callable<String>() {

@Override
public String call() throws Exception {
if ("1".equalsIgnoreCase(key)) {
return "test";
}
throw new Exception("This is a test!");
}

});
return rr;
}

public static void main(String[] args) throws Exception {
System.out.println(GuavaCache.get("1"));
System.out.println("before expire: " + GuavaCache.caches.asMap().keySet());
Thread.sleep(5000);
System.out.println("after expire: " + GuavaCache.caches.asMap().keySet());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: