【发布时间】:2017-02-08 09:08:56
【问题描述】:
我正在尝试使用 Google Guava Cache 按服务相关对象进行缓存。在缓存未命中时,我使用我的 REST 客户端来获取对象。我知道我可以通过以下方式做到这一点:
CacheLoader<Key, Graph> loader = new CacheLoader<Key, Graph>() {
public Graph load(Key key) throws InternalServerException, ResourceNotFoundException {
return client.get(key);
}
};
LoadingCache<Key, Graph> cache = CacheBuilder.newBuilder().build(loader)
现在,client.getKey(Key k) 实际上会抛出 InternalServerException 和 ResourceNotFoundException。当我尝试使用此缓存实例获取对象时,我可以将异常捕获为ExecutionException。
try {
cache.get(key);
} catch (ExecutionException e){
}
但是,我想专门捕获和处理我定义的 CacheLoader 抛出的异常(即InternalServerException 和ResourceNotFoundException)。
我不确定检查ExecutionException 的实例是否是我自己的异常之一是否会起作用,因为load() 方法的签名实际上会抛出Exception 而不是ExecutionException。即使我可以使用instanceof,它似乎也不是很干净。有什么好的方法来解决这个问题吗?
【问题讨论】:
标签: java guava google-guava-cache