gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 03:29:54 24 4
gpt4 key购买 nike

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

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 显然忽略了 version 字段的值——它的含义由用户定义。所以 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.


我想使用 version 字段可能会导致竞争条件,导致一个线程用某个较旧的版本覆盖缓存项的最新版本。因此,在我的应用程序中,我有一个计数器来跟踪数据库的最新版本,并且当我使用不同于最新数据库版本的 version 字段加载缓存值时-value,我知道缓存的值可能过时并忽略它。

关于java - 如何在 EHCache 实例中使用元素版本控制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3148476/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com