guava实现本地缓存

来源:互联网 发布:photoshop软件功能 编辑:程序博客网 时间:2024/06/10 07:56
private static  LoadingCache<String, String> cache =        //CacheBuilder的构造函数是私有的,只能通过其静态方法newBuilder()来获得CacheBuilder的实例        CacheBuilder.newBuilder()                //设置并发级别为8,并发级别是指可以同时写缓存的线程数                .concurrencyLevel(8)                //设置写缓存后30分钟过期                .expireAfterWrite(30, TimeUnit.MINUTES)                //设置缓存容器的初始容量为10                .initialCapacity(10)                //设置缓存最大容量为100,超过100之后就会按照LRU最近虽少使用算法来移除缓存项                .maximumSize(100)                //设置要统计缓存的命中率                .recordStats()                //设置缓存的移除通知                .removalListener(new RemovalListener<Object, Object>() {                 public  void onRemoval(RemovalNotification<Object, Object> notification) {                        System.out.println(notification+"was removed, cause is "+ notification.getCause());                    }                })                //build方法中可以指定CacheLoader,在缓存不存在时通过CacheLoader的实现自动加载缓存                .build(new CacheLoader<String,String>() {                            public String load(String str) throws Exception {                                return str + " SPF";                            };                        }

);

public static void main(String[] args) throws ExecutionException {
String s = cache.get("Hi");
System.out.println(s);
}

原创粉丝点击