我正在尝试创建一个简单的 session 缓存,它允许我设置整个缓存的最大大小。缓存不是计算缓存,所以我觉得Guava的CacheBuilder
加上一个LoadingCache
是不合适的。我希望能够执行以下操作:
get(key)
来自先前在存储操作期间存储的缓存的数据
在存储操作期间将(key,value)
放入缓存
我尝试使用 MapMaker,但最大尺寸方法似乎过时了。有谁知道我有什么选择?我想我总是可以只使用一个简单的 map 并滚动我自己的策略吗?
最佳答案
The cache is not a computing cache, so I think Guava's
CacheBuilder
with aLoadingCache
is not appropriate.
所以在没有它的情况下使用CacheBuilder
。它的工作原理完全相同,只是如果 build(CacheLoader)
调用普通的 build()
而不是。一切都保持不变,除了你得到一个“正常”缓存而不是加载缓存。就这样。
I tried using MapMaker but the maximum size method seems to be antiquated.
通过 MapMaper
进行缓存总有一天会消失,算了吧。
例子很简单,直接创建
private final static Cache<String, String> cache =
CacheBuilder.newBuilder().maximumSize(123).build();
然后试试这个:
cache.put("a", "A");
cache.put("b", "B");
System.out.println(cache.getIfPresent("a"));
for (int i=0; i<1000; ++i) cache.put("n" + i, "x");
System.out.println(cache.getIfPresent("a"));
关于java - Guava 基于策略的缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11909476/