我正在使用EHCache 3.5.2并且无法获取所有缓存密钥和缓存条目。
我正在使用CacheManager来创建缓存。然后我用一些数据填充它。然后我想找回……
按照设计,这不是Ehcache中的简单API调用。由于它支持的分层模型,实现堆上的所有键或值可能导致JVM耗尽内存。
如其他答案所示,有办法实现这一目标。
但它被认为是一种缓存反模式,必须立即获取缓存的全部内容。
我找到了一种方法来做到这一点,但它有点味道:
Set<String> keys = new HashSet<>(); cache.forEach(entry -> keys.add(entry.getKey())); List<Foo> foos = cache.getAll(keys).values().stream().collect(toList())
为什么不这样的?
Map<String, Foo> foos = StreamSupport.stream(cache.spliterator(), false) .collect(Collectors.toMap(Cache.Entry::getKey, Cache.Entry::getValue));
要么
List<Cache.Entry<String, Foo>> foos = StreamSupport.stream(cache.spliterator(), false) .collect(Collectors.toList());
或(旧式)
List<Cache.Entry<String, Foo>> foos = new ArrayList<>(); for(Cache.Entry<String, Foo> entry : cache) { foos.add(entry); }