轻量级 Java 对象缓存 API

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

Lightweight Java Object cache API

javacaching

提问by Chase Seibert

Question

I'm looking for a Java in-memory object caching API. Any recommendations? What solutions have you used in the past?

我正在寻找 Java 内存对象缓存 API。有什么建议吗?您过去使用过哪些解决方案?

Current

当前的

Right now, I'm just using a Map:

现在,我只是使用地图:

Map cache = new HashMap<String, Object>();
cache.put("key", value);

Requirements

要求

I need to extend the cache to include basic features like:

我需要扩展缓存以包含基本功能,例如:

  • Max size
  • Time to live
  • 最大尺寸
  • 生活时间

However, I don't need more sophisticated features like:

但是,我不需要更复杂的功能,例如:

  • Access from multiple processes (caching server)
  • Persistence (to disk)
  • 从多个进程访问(缓存服务器)
  • 持久性(到磁盘)

Suggestions

建议

In-Memory caching:

内存缓存:

  • GuavaCacheBuilder - active development. See this presentation.
  • LRUMap- Config via API. No TTL. Not purpose built for caching.
  • whirlycache- XML config. Mailing list. Last updated 2006.
  • cache4j- XML config. Documentation in Russian. Last updated 2006.
  • GuavaCacheBuilder - 积极开发。请参阅此演示文稿
  • LRUMap- 通过 API 配置。没有TTL。不是专为缓存而构建的。
  • whirlycache- XML 配置。邮件列表。最后更新 2006 年。
  • cache4j- XML 配置。俄文文档。最后更新 2006 年。

Enterprise caching:

企业缓存:

  • JCS- Properties config. Extensive documentation.
  • Ehcache- XML config. Extensive documentation. By far the most popular according to Google hits.
  • JCS- 属性配置。广泛的文档。
  • Ehcache- XML 配置。广泛的文档。到目前为止,根据谷歌点击量是最受欢迎的。

采纳答案by Steve K

EHCacheis very nice. You can create an in memory cache. Check out their code samplesfor an example of creating an in memory cache. You can specify a max size, and a time to live.

EHCache非常好。您可以创建内存缓存。查看他们的代码示例,了解创建内存缓存的示例。您可以指定最大大小和生存时间。

EHCache does offer some advanced features, but if your not interested in using them - don't. But it's nice to know they are there if your requirements ever change.

EHCache 确实提供了一些高级功能,但如果您对使用它们不感兴趣 - 不要。但是,如果您的需求发生变化,很高兴知道他们在那里。

Here is an in memory cache. Created in code, with no configuration files.

这是一个内存缓存。用代码创建,没有配置文件。

CacheManager cacheManager = CacheManager.getInstance();
int oneDay = 24 * 60 * 60;
Cache memoryOnlyCache = new Cache("name", 200, false, false, oneDay, oneDay);
cacheManager.addCache(memoryOnlyCache);

Creates a cache that will hold 200 elements, and has a ttl of 24 hours.

创建一个可容纳 200 个元素且 ttl 为 24 小时的缓存。

回答by Ichorus

JCSis tried and true. Even though it is light as far as caching mechanisms go, you might dig into the actual code and mimic what they do with HashMap under the covers to exactly what you need and no more. You seem to have a pretty good idea of what you are looking for.

JCS 久经考验。尽管就缓存机制而言它是轻量级的,但您可能会深入研究实际代码并在幕后模仿它们对 HashMap 所做的事情,以完全满足您的需要,仅此而已。你似乎很清楚你在寻找什么。

回答by JeeBee

You can check out LinkedHashMap to implement a simple cache without third party jars:

您可以查看 LinkedHashMap 来实现一个没有第三方 jar 的简单缓存:

    Map <String, Foo> cache = new LinkedHashMap<String, Foo>(MAX_ENTRIES + 1, .75F, true) {

        public boolean removeEldestEntry(Map.Entry<String, Foo> eldest) {
            return size() > MAX_ENTRIES;
        }
    };

then you can get from the cache like

然后你可以从缓存中获取

    Foo foo = cache.get(key);
    if (foo == null && !cache.containsKey(key)) {
        try {
            FooDAO fooDAO = DAOFactory.getFooDAO(conn);
            foo = fooDAO.getFooByKey(key);
            cache.put(key, foo);
        } catch (SQLException sqle) {
            logger.error("[getFoo] SQL Exception when accessing Foo", sqle);
        }
    }

rest left as exercise for reader :)

休息留给读者练习:)

回答by Travis Reeder

You can also check out my little cache library called KittyCache at:

您还可以在以下位置查看我的名为 KittyCache 的小型缓存库:

https://github.com/treeder/kitty-cache

https://github.com/treeder/kitty-cache

There are some performance benchmarks vs ehcache.

有一些性能基准与 ehcache。

It's used in the SimpleJPAproject as a second level cache.

它在SimpleJPA项目中用作二级缓存。

回答by Joachim Sauer

I really like the MapMakerthat comes with Google Guava(API)

我真的很喜欢Google Guava( API)MapMaker附带的

The JavaDoc has a pretty neat example that demonstrates both its ease of use and its power:

JavaDoc 有一个非常简洁的例子,展示了它的易用性和强大的功能:

ConcurrentMap<Key, Graph> graphs = new MapMaker()
   .concurrencyLevel(32)
   .softKeys()
   .weakValues()
   .expiration(30, TimeUnit.MINUTES)
   .makeComputingMap(
       new Function<Key, Graph>() {
         public Graph apply(Key key) {
           return createExpensiveGraph(key);
         }
       });

Furthermore, release 10.0 of Guava introduced the much more extensive com.google.common.cachepackage(there's a nice wiki entry on how to use them).

此外,Guava 10.0 版引入了更广泛的com.google.common.cache关于如何使用它们有一个很好的 wiki 条目)。

回答by Zorkus

memcached has client for Java. http://www.danga.com/memcached/Requires separate process to be a caching server, but powerful thing.

memcached 有 Java 客户端。http://www.danga.com/memcached/需要单独的进程作为缓存服务器,但功能强大。

回答by Bohemian

Guava's MapMakerhas been replaced by their CacheBuilderclass.

Guava 的MapMaker已被它们的CacheBuilder类取代。