如何在EHCache实例中使用元素版本控制?

我正在缓存以异步方式发送到我的组件的对象.换句话说,这些对象到达的顺序是不可预测的.为了避免任何问题,我在我的对象中包含了一个版本属性(基本上是一个时间戳).这个想法是任何到达的对象的版本比已经缓存的版本更旧,它可以被丢弃.

EHCache的“Element”类(包装EHCache中的对象)似乎有助于此:除了键和值之外,构造函数可以采用(基于长度的)版本.我不能按照我希望它工作的方式来完成这项工作.以下代码片段演示了我的问题(使用EHCache 2.1.1):

public static void main(String[] args) {
    final CacheManager manager = CacheManager.create();
    final Cache testCache = new Cache(new CacheConfiguration("test", 40));
    manager.addCache(testCache);

    final String key = "key";
    final Element elNew = new Element(key, "NEW", 2L);
    testCache.put(elNew);
    final Element elOld = new Element(key, "OLD", 1L);
    testCache.put(elOld);

    System.out.println("Cache content:");
    for (Object k : testCache.getKeys()) {
        System.out.println(testCache.get(k));
    }
}

我希望上面的代码使缓存的值为“NEW”,而是打印“OLD”.如果你对插入元素的顺序稍微玩一下,你会发现最后一个插入元素的是保留在缓存中的那个.版本控制似乎被忽略了.

我没有正确使用版本控制功能,还是不打算用于此目的?谁能推荐替代品?

最佳答案 EhCache显然忽略了版本字段的值 – 其含义由用户定义.所以EhCache用版本1L覆盖你的版本2L而不知道版本号是什么意思.

见1)http://jira.terracotta.org/jira/browse/EHC-765

it was decided that providing an internal versioning scheme would
cause unnecessary overhead for all users. Instead we now leave the
version value untouched so that it is entirely within the control of
the user.

并且2)http://jira.terracotta.org/jira/browse/EHC-666

[…] I would much prefer the solution proposed by Marek, that we grant the
user complete control over the version attribute and to not mutate it
at all internally. This prevents there being any performance impact
for the bulk of users, and allows the user the flexibility to use it
as they see fit. […]

As agreed with Greg via email I fixed this as
per my last comment.

我想使用版本字段可能会导致竞争条件,导致一个线程覆盖一个缓存项目的最新版本与一些旧的版本.因此,在我的应用程序中,我有一个计数器,可以跟踪最新版本的数据库,当我加载一个缓存值的版本字段不同于最新的数据库版本值时,我知道缓存的值可能是陈旧的并忽略它.

点赞