值为空时如何避免缓存? [英] How to avoid caching when values are null?
问题描述
我正在使用番石榴来缓存热数据。当缓存中不存在数据时,我必须从数据库中获取数据:
I am using Guava to cache hot data. When the data does not exist in the cache, I have to get it from database:
public final static LoadingCache<ObjectId, User> UID2UCache = CacheBuilder.newBuilder()
//.maximumSize(2000)
.weakKeys()
.weakValues()
.expireAfterAccess(10, TimeUnit.MINUTES)
.build(
new CacheLoader<ObjectId, User>() {
@Override
public User load(ObjectId k) throws Exception {
User u = DataLoader.datastore.find(User.class).field("_id").equal(k).get();
return u;
}
});
我的问题是数据库中不存在数据时,我希望它返回 null
并且不进行任何缓存。但是番石榴用缓存中的键保存 null
并在我得到它时引发异常:
My problem is when the data does not exists in database, I want it to return null
and to not do any caching. But Guava saves null
with the key in the cache and throws an exception when I get it:
com.google.common.cache.CacheLoader $ InvalidCacheLoadException:
CacheLoader为密钥shisoft返回null。
com.google.common.cache.CacheLoader$InvalidCacheLoadException: CacheLoader returned null for key shisoft.
我们如何避免缓存 null
值?
推荐答案
只抛出一些异常如果找不到用户并在使用 get(key)
方法。
Just throw some Exception if user is not found and catch it in client code while using get(key)
method.
new CacheLoader<ObjectId, User>() {
@Override
public User load(ObjectId k) throws Exception {
User u = DataLoader.datastore.find(User.class).field("_id").equal(k).get();
if (u != null) {
return u;
} else {
throw new UserNotFoundException();
}
}
}
来自 CacheLoader.load(K)
Javadoc:
From CacheLoader.load(K)
Javadoc:
Returns:
the value associated with key; must not be null
Throws:
Exception - if unable to load the result
回答关于缓存空值的疑问:
Answering your doubts about caching null values:
首先返回与此缓存中的键关联的值。如有必要,加载
该值。 在加载完成之前,不会修改与此
缓存相关的可观察状态。
(来自 LoadingCache.get(K)
Javadoc)
如果抛出异常,则认为加载未完成,因此不会缓存任何新值。
If you throw an exception, load is not considered as complete, so no new value is cached.
EDIT :
请注意,在咖啡因中,它是Guava缓存2.0的一种,并且提供了-使用Google Guava启发的API进行内存缓存,您 可以从 load返回
方法: null
Note that in Caffeine, which is sort of Guava cache 2.0 and "provides an in-memory cache using a Google Guava inspired API" you can return null
from load
method:
Returns:
the value associated with key or null if not found
考虑进行迁移,当找不到用户时,您的数据加载器可以自由返回。
If you may consider migrating, your data loader could freely return when user is not found.
这篇关于值为空时如何避免缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!