我有这种方法从数据库加载大量数据
private List<Something> loadFromDb() {
//some loading which can take a lot of time
}
Run Code Online (Sandbox Code Playgroud)
我正在寻找一种简单的方法来缓存一些固定时间的结果(例如2分钟).我不需要拦截方法调用本身,只是为了缓存返回的数据 - 如果需要,我可以编写另一个执行缓存的方法.
我不想:
@Cacheable在Spring中使用- 我必须为每个可缓存方法定义一个缓存是否有可以简化此任务的库,还是应该执行其他操作?这种库的示例使用将是
private List<Something> loadFromDbCached() {
//in java 8 'this::loadFromDb' would be possible instead of a String
return SimpleCaching.cache(this, "loadFromDb", 2, MINUTES).call();
}
Run Code Online (Sandbox Code Playgroud)
编辑: 我正在寻找一个这样做的库,管理缓存比看起来更麻烦,特别是如果你有并发访问
thS*_*oft 13
使用Guava的Suppliers.memoizeWithExpiration(供应商代表,持续时间长,TimeUnit单位):
private final Supplier<List<Something>> cache =
Suppliers.memoizeWithExpiration(new Supplier<List<Something>>() {
public List<Something> get() {
return loadFromDb();
}
}, 2, MINUTES);
private List<Something> loadFromDbCached() {
return cache.get();
}
Run Code Online (Sandbox Code Playgroud)