源码:
private static Cache<String, String> cacheFormCallable = null;
public static <K, V> Cache<K, V> callableCached() throws Exception {
Cache<K, V> cache = CacheBuilder.newBuilder().maximumSize(10000).expireAfterWrite(10, TimeUnit.MINUTES).build();
return cache;
}
private String getCallableCache(final String userName) {
try {
// Callable只有在缓存值不存在时,才会调用
return cacheFormCallable.get(userName, new Callable<String>() {
@Override
public String call() throws Exception {
System.out.println(userName + " from db");
return "hello " + userName + "!";
}
});
} catch (ExecutionException e) {
e.printStackTrace();
return null;
}
}