我正在尝试使用 Guava 缓存库创建缓存。我的主要要求之一是我想在 CacheLoader.load(..) 函数之后设置缓存过期,而不是我在网络上遇到的大多数示例,如下所示。
LoadingCache<String, MyClass> myCache =
CacheBuilder.newBuilder().maximumSize(MAX_SIZE).expireAfterWrite(10, TimeUnit.Minutes).build(cacheLoader);
原因是 CacheLoader.load(...) 函数从数据库检索的对象包含过期数据。所以我想使用这些信息而不是一些“随机”静态值。
我想要这样的东西。
LoadingCache<String, MyClass> myCache =
CacheBuilder.newBuilder().maximumSize(MAX_SIZE).build(cacheLoader);
...
CacheLoader meCacheLoder = new CacheLoader<String MyClass>(){
@Override
public MyClass load(String key) throws Exception {
// Retrieve the MyClass object from database using 'key'
MyClass myObj = getMyObjectFromDb(key);
int expiry = myObj.getExpiry();
// Now somehow set this 'expiry' value with the cache
????
return myObj;
}
};
或 为此,是否有比 Guava 缓存更好的选择?
最佳答案
正如 Louis 已经指出的那样,Guava 中没有这样的功能。
例如,您可以使用 EHCache 或 cache2k 。对于cache2k,我可以为您提供快速指导,因为这是我们经常使用的核心功能:
您可以在值对象上实现接口(interface)ValueWithExpiryTime
,即:
interface ValueWithExpiryTime {
long getCacheExpiryTime();
}
或者,您可以注册一个 EntryExpiryCalculator
来提取时间值。缓存构建如下:
Cache<Key, Value> cache =
CacheBuilder.newCache(Key.class, Value.class)
.expiryCalculator(new EntryExpiryCalculator<Key, Value>() {
@Override
public long calculateExpiryTime(
final Key key, final Value value,
final long loadTime, final CacheEntry<Key, Value> oldEntry) {
return value.getExpiry();
}
}
)
.build();
时间是标准长类型,以纪元以来的毫秒数表示。默认情况下,到期不会恰好在指定时间发生,而是在零或几毫秒后发生,具体取决于您的计算机负载。这是最有效的模式。如果这是一个问题,请添加 sharpExpiry(true)
。
免责声明:我是cache2k的作者......
关于java - Guava 缓存 : how to set expiration on 'CacheLoader.load()' instead of during CacheBuilder. newBuilder()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36226664/