Ehcache - 在数据不存在时使用SelfPopulatingCache [英] Ehcache - using SelfPopulatingCache when data is not present

查看:155
本文介绍了Ehcache - 在数据不存在时使用SelfPopulatingCache的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用EhCache的装饰器 SelfPopulatingCache 并且当缓存尝试加载新条目时出现问题,但它不存在(即它不存在于数据库)。因此缓存会将一个 null 值放入缓存中,以解除对该密钥的任何其他获取的阻止,但随后下一个线程将执行相同的数据库调用,因为它收到了'null '来自缓存。这意味着它认为需要加载条目 - 即使实际上它是空的,因为数据不存在于任何地方。我觉得我做错了。

I am using the EhCache's decorator SelfPopulatingCache and have an issue when the cache tries to load a new entry, but it's non-existent (i.e. it doesn't exist in the database). So the cache will put a null value into the cache, to unblock any other gets on the key, but then the next thread will do the same database call because it received 'null' from the cache. which means it thinks the entry needs to be loaded - even though in reality it's null because the data doesn't exists anywhere. I feel like I'm doing something wrong.

(伪代码)

Value v = cache.get(key); // multiple threads will block here
if (v == null)
   cache.put(key, getValueFromDB()); // this might put a null value

我当前的解决方案是不放空,而是放一个占位符对象并检查它。

My current solution is to not put null, but to put a placeholder Object and check for it.

Value v = cache.get(key);
if (v == null)
   cache.put(key, getValueFromDB());
else if (v == NOENTRYOBJECT)
   return null;
else
   return v;

想法?

推荐答案

我们做类似的事情。在我们的例子中,如果请求的密钥与有效项不对应,我们将 Boolean.FALSE 输入缓存。它基本上告诉调用代码它要求的密钥与任何数据都不匹配。您需要在第一次请求该密钥时对数据库进行一次调用,以发现它与有效数据不对应,但后续调用不会进行数据库查找。当然,如果数据曾经输入到该密钥的数据库中,则需要确保使该缓存条目无效(否则即使有可用的实际数据,您也将返回Boolean.FALSE)。

We do something similar. In our case, we enter Boolean.FALSE into the cache if the requested key doesn't correspond to a valid item. It basically tells the calling code that the key that it asked for doesn't match any data. You need to make one call to the db on the first request for that key to discover that it doesn't correspond to valid data, but subsequent calls are spared the db lookup. Of course, if data is ever entered into the db for that key, you need to be sure to invalidate that cache entry (otherwise you'll be returning Boolean.FALSE even though there is actual data available).

不确定我的回复是否有多大帮助(这不是一种替代方法),但它至少证实了你的方法并不孤单。

Not sure if my response helps that much (it's not an alternative approach), but it at least validates that you're not alone in your approach.

BTW,我不认为这是EHCache的SelfPopulatingCache独有的。

BTW, I don't think this is unique to EHCache's SelfPopulatingCache.

这篇关于Ehcache - 在数据不存在时使用SelfPopulatingCache的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆