简单的 Java 缓存库还是设计模式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13158657/
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-10-31 11:41:56  来源:igfitidea点击:

Simple Java caching library or design pattern?

javadesign-patternscachingmemcachedehcache

提问by nn4l

I need to frequently access the result of a time-consuming calculation. The result changes infrequently, so I have to recalculate the data from time to time but it is ok to use the outdated result for a while. What would be the easiest way to do this and is there an existing library method or design pattern?

我需要经常访问耗时计算的结果。结果很少变化,所以我要不时重新计算数据,但使用过时的结果一段时间是可以的。什么是最简单的方法,是否有现有的库方法或设计模式?

I am thinking of something like

我在想类似的事情

private static List myCachedList = null;

...

// refresh list once in 3600 seconds
if (needsRefresh(myCachedList, 3600)) {
    // run the calculation
    myCachedList = ...
}
// use either updated or previous value from here on

A proper implementation might not be trivial, it might have to deal with thread safety, race conditions etc., so I would rather use a proven implementation than roll my own here.

一个正确的实现可能不是微不足道的,它可能必须处理线程安全、竞争条件等,所以我宁愿使用经过验证的实现而不是在这里推出我自己的实现。

回答by Brian Agnew

Congratulations for realising that writing your own can be more trouble it initially appears!

恭喜您意识到编写自己的代码可能会比最初出现的更麻烦!

I would check out the Guava cachesolution. Guava is a proven library and the caches are easily available (and configurable) via a fluent factory API.

我会查看Guava 缓存解决方案。Guava 是一个经过验证的库,可以通过流畅的工厂 API 轻松获得(和配置)缓存。

All Guava caches, loading or not, support the method get(K, Callable<V>). This method returns the value associated with the key in the cache, or computes it from the specified Callable and adds it to the cache. No observable state associated with this cache is modified until loading completes. This method provides a simple substitute for the conventional "if cached, return; otherwise create, cache and return" pattern.

所有 Guava 缓存,无论是否加载,都支持 get(K, Callable<V>) 方法。此方法返回与缓存中的键关联的值,或者从指定的 Callable 计算它并将其添加到缓存中。在加载完成之前,不会修改与此缓存关联的可观察状态。此方法为传统的“如果缓存,则返回;否则创建,缓存并返回”模式提供了简单的替代。

回答by tjg184

I would take a look at Google guava-libraries. Much of this work has already been done for you.

我会看看 Google guava-libraries。大部分工作已经为您完成。

There's specifically a section called Timed Eviction, which might be related to what you want. https://github.com/google/guava/wiki/CachesExplained#timed-eviction

特别有一个名为 Timed Eviction 的部分,它可能与您想要的有关。 https://github.com/google/guava/wiki/CachesExplained#timed-eviction

回答by fredcrs

I would suggest for you to use the Proxy Design Pattern that way you can encapsulate the caching logic-implementation in your proxy class

我建议您使用代理设计模式,这样您就可以将缓存逻辑实现封装在代理类中

theres a cool example here that looks like to fit your needs

这里有一个很酷的例子,看起来很适合你的需求

http://en.wikipedia.org/wiki/Proxy_pattern

http://en.wikipedia.org/wiki/Proxy_pattern

回答by Ramesha.C

if you do not want to use third party library, simply you can create a static map which holds the key and value. using key you can retrieve the data fast.

如果您不想使用第三方库,只需创建一个包含键和值的静态映射即可。使用密钥可以快速检索数据。

and write methods to add values to cache, get, remove.

并编写方法来添加值到缓存、获取、删除。

public SimpleCache{
    private static Map<String,Object> simpleCache = new HashMap<>();

    public static <T> T getValue(String key, Class type){

    //todo check contains here, if map doesn't contains key, throw not found exception

    Object val = simpleCache.get(key);

    return (T)val;    
  }
}

hope this helps

希望这可以帮助