java 在java中缓存方法的结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17088812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:55:47  来源:igfitidea点击:

Caching the result of a method in java

javacaching

提问by jmruc

I have this method that loads a lot of data from the database

我有这种从数据库加载大量数据的方法

private List<Something> loadFromDb() {
    //some loading which can take a lot of time
}

I am looking for a simpleway to cache the results for some fixed time (2 minutes for example). I do not need to intercept the method invocation itself, just to cache the returned data- I can write another method that does the caching if necessary.

我正在寻找一种简单的方法来缓存某个固定时间(例如 2 分钟)的结果。我不需要拦截方法调用本身,只是为了缓存返回的数据- 如果需要,我可以编写另一个进行缓存的方法。

I don't want to:

我不想:

  • Use AOP compile time weaving like this one- it requires changes in the build
  • Use @Cacheablein Spring - I have to define a cache for each cacheable method
  • 这样使用 AOP 编译时编织- 它需要在构建中进行更改
  • @Cacheable在 Spring 中使用- 我必须为每个可缓存的方法定义一个缓存

Is there a library which can simplify this task, or should I do something else? An example use of such library would be

是否有可以简化此任务的库,或者我应该做其他事情吗?使用此类库的示例是

private List<Something> loadFromDbCached() {
    //in java 8 'this::loadFromDb' would be possible instead of a String
    return SimpleCaching.cache(this, "loadFromDb", 2, MINUTES).call();
}

EDIT:I am looking for a library that does that, managing the cache is more trouble than it seems, especially if you have concurrent access

编辑:我正在寻找一个这样做的库,管理缓存比看起来更麻烦,特别是如果你有并发访问

回答by thSoft

Use Guava's Suppliers.memoizeWithExpiration(Supplier delegate, long duration, TimeUnit unit):

使用 Guava 的Suppliers.memoizeWithExpiration(Supplier delegate, long duration, TimeUnit unit)

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();
}

回答by Arnab Biswas

Check Guava Cache BuilderIt may be useful.

检查Guava Cache Builder可能有用。

回答by yegor256

You can use @Cacheableannotation from jcabi-aspects:

您可以使用jcabi-aspects 中的@Cacheable注释:

public class Resource {
  @Cacheable(lifetime = 5, unit = TimeUnit.SECONDS)
  public String load(URL url) {
    return url.openConnection().getContent();
  }
}

The result of load()will be cached for five seconds. Check this article, it explains the details: http://www.yegor256.com/2014/08/03/cacheable-java-annotation.html

的结果load()将被缓存五秒钟。检查这篇文章,它解释了详细信息:http: //www.yegor256.com/2014/08/03/cacheable-java-annotation.html