例如,你可以用下面的代码构建LoadingCache:
@Test
public void LoadingCache() throws Exception{
LoadingCache<String,String> cahceBuilder=CacheBuilder
.newBuilder().maximumSize(10000).expireAfterAccess(10, TimeUnit.MINUTES)
.build(new CacheLoader<String, String>(){
@Override
public String load(String key) throws Exception {
return createExpensiveGraph(key);
}
private String createExpensiveGraph(String key) {
System.out.println("load into cache!");
return "hello "+key+"!";
}
});
cahceBuilder.get("2");
cahceBuilder.get("3");
//第二次就直接从缓存中取出
cahceBuilder.get("2");
} @Test
public void callableCache()throws Exception{
Cache<String, String> cache = CacheBuilder.newBuilder().maximumSize(1000).expireAfterAccess(10, TimeUnit.MINUTES).build();
//这里可以手動进行缓存
cache.put("1", "I'm in chche");
//-----------------------------------------------
final String key1 = "1";
String resultVal = cache.get(key1, new Callable<String>() {
public String call() {
return createExpensiveGraph(key1);
}
});
System.out.println("1 value : " + resultVal);
//-------------------------------------------------
resultVal = cache.get("2", new Callable<String>() {
public String call() {
return createExpensiveGraph(key1);
}
});
System.out.println("2 value : " + resultVal);
//==================================================
}
protected String createExpensiveGraph(String string) {
return "hello "+string+"!";
}原文:http://blog.csdn.net/u012516914/article/details/43483125