Java Guava组合Multimap和Cache [英] Java Guava combination of Multimap and Cache
问题描述
是否有可用的组合Guava的缓存
和 Multimap
功能?基本上,我需要一个集合,其中条目在给定时间后过期,例如 Cache
中可用,但我有非唯一键,我需要条目独立到期。
Is there any such thing as a combination of Guava's Cache
and Multimap
functionality available? Essentially, I need a collection where entries expire after a given time such as available in Cache
but I have non-unique keys and I need the entries to expire independently.
推荐答案
我认为Louis Wasserman在上面的一条评论中提供了答案,即没有现成的组合 Multimap
和缓存
可用。我已用下面的伪代码中概述的解决方案解决了我的问题/要求:
I think that Louis Wasserman provided the answer in one of the comments above, i.e. that there is no off-the-shelf combo of Multimap
and Cache
available. I have solved my problem/requirements with the solution outlined in pseudo-code below:
private Cache<Integer,Object> cache = CacheBuilder.newBuilder().SomeConfig.build();
private Multimap<Integer,Object> multimap = HashMultimap<Integer, Object>.create();
private AtomicInteger atomicid = new AtomicInteger(0);
public void putInMultimap(int id, Object obj) {
int mapid = atomicid.addAndGet(1);
cache.put(mapid,obj);
multimap.put(id,mapid);
}
public List<Object> getFromMultimap(int id) {
Set<Integer> mapids = multimap.get(id);
List<Object> list = new ArrayList<Object>();
for (int i : mapids) {
list.add(cache.getIfPresent(i));
}
return list;
}
这个简单的解决方案有一些限制,但它对我来说没问题。
This simple 'solution' has some limitations but it works OK for me.
这篇关于Java Guava组合Multimap和Cache的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!