问题描述
我有兴趣了解Google guava 11.0库中引入的loadAll方法实现的有效方法是什么.
I am interested in knowing what is the effective way of loadAll method implementation introduced in google guava 11.0 library.
以下是描述加载扩展的所有方法实现的以下代码
按照CachesExplained
Here is the following code that describes load all method implementation extended
as per the example from CachesExplained
LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder().maximumSize(1000)
.refreshAfterWrite(1, TimeUnit.MINUTES)
.build(
new CacheLoader<Key, Graph>() {
public Graph load(Key key) { // no checked exception
return getGraphFromDatabase(key);
}
public Map<Key, Graph> loadAll(Iterable<? extends K> keys) {
return getAllGraphsFromDatabase(keys);
}
}
);
private Map<Key, Graph> getAllGraphsFromDatabase(Iterable<? extends key> keys)
{
lListOfGraph = //resultset got from DB Call
for (lCount = 0; lCount < lListOfGraph.size(); lCount++)
{
lGraph = (Graph)lListOfGraph.get(lCount).get(0);
graphs.asMap().put((key , lGraph);
}
return (Map<key, Graph>) graphs;
}
此处的返回类型Map抛出错误java.lang.ClassCastException:com.google.common.cache.LocalCache $ LocalLoadingCache无法转换为java.util.Map(知道Loading Cache对象不能为类型的事实地图)
Here return type that is Map throws error java.lang.ClassCastException:com.google.common.cache.LocalCache$LocalLoadingCache cannot be cast to java.util.Map (Knowing the fact that Loading Cache object can not be of type Map)
如果这不是使用LoadingCache的正确实现方式,则如何将数据注入到LoadingCache的Component中,以便可以将其用作Cache.
If this is not the correct way of implementation of using LoadingCache thenHow is the data injected in LoadingCache's Component so that it can be used as Cache.
推荐答案
您的getAllGraphsFromDatabase
方法应该从基础数据存储中获取值. LoadingCache
实现为您处理将返回的值添加到地图中的过程.
Your getAllGraphsFromDatabase
method should be fetching the values from the underlying data store. The LoadingCache
implementation handles adding the returned values to the map for you.
我认为您的加载方法应如下:
I think your loading method should look like:
private Map<Key, Graph> getAllGraphsFromDatabase(Iterable<? extends key> keys)
{
final List<Graph> lListOfGraph = //resultset got from DB Call
final Map<Key, Graph> map = new HashMap<Key, Graph>(listOfGraph.size());
for (final Graph graph : lListOfGraph)
map.put(graph.getKey(), graph);
return map;
}
这篇关于Google Guava的CacheLoader loadAll()方法实现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!