ITeye博客

com.google.common.cache.CacheLoader 本地緩存的使用方法

liumayulingyan · 2014-06-19 13:58 · 应用 · 行业应用 · Markdown

http://blog.sina.com.cn/s/blog_a2ec891e0101a20v.html

 

 

package com.taobao.ju.my.common.biz.manager.impl;

 

import java.util.concurrent.Callable;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.TimeUnit;

 

import com.google.common.cache.Cache;

import com.google.common.cache.CacheBuilder;

import com.google.common.cache.CacheLoader;

import com.google.common.cache.LoadingCache;

 

public class LoadingCacheDemo {

public static void main(String[] args) throws ExecutionException {

//方法一

//创建本地缓存,当本地缓存不命中时,调用load方法,返回结果,再缓存结果。

LoadingCache loadingCache = CacheBuilder.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS).maximumSize(10000).build(new CacheLoader() {

@Override

public String load(String key) throws Exception {

return getString(key);

}

});

 

loadingCache.get("test");

loadingCache.get("test2");

//方法二

//创建缓存对像

Cache cache = CacheBuilder.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS).maximumSize(10000).build();

 

//调用缓存中的get方法,当缓存命中时直接返回结果,当不命中时,通过给定的Callable类call方法 返回结果,再缓存。这个方法

//到更灵活,可以用一个cache对象缓存多种不同的数据,只要用不同的Callable对象就行。

cache.get("111", new Callable() {

@Override

public String call() throws Exception {

System.out.println("经过 call()");

return "value.";

}

});

 

cache.get("222", new Callable() {

@Override

public String call() throws Exception {

System.out.println("经过 call()");

return "value.";

}

});

}

 

public static String getString(String key) {

System.out.println("经过 getString()");

return key + "--Test";

}

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。