我正在尝试让番石榴缓存为我的应用程序工作。 具体来说,我基本上是在寻找一个行为类似于地图的缓存:
// Here the keys are the User.getId() and the values are the respective User.
Map<Long, User> userCache = new HashMap<Long, User>();
来自各种在线资源(文档、博客、文章等):
// My POJO.
public class User {
Long id;
String name;
// Lots of other properties.
}
public class UserCache {
LoadingCache _cache;
UserCacheLoader loader;
UserCacheRemovalListener listener;
UserCache() {
super();
this._cache = CacheBuilder.newBuilder()
.maximumSize(1000)
.expireAfterAccess(30, TimeUnit.SECONDS)
.removalListener(listener)
.build(loader);
}
User load(Long id) {
_cache.get(id);
}
}
class UserCacheLoader extends CacheLoader {
@Override
public Object load(Object key) throws Exception {
// ???
return null;
}
}
class UserCacheRemovalListener implements RemovalListener<String, String>{
@Override
public void onRemoval(RemovalNotification<String, String> notification) {
System.out.println("User with ID of " + notification.getKey() + " was removed from the cache.");
}
}
但我不确定如何/在哪里指定键应该是Long
类型,缓存值应该是User
实例。我还希望实现一个store(User)
(基本上是一个Map#put(K,V)
)方法以及一个返回缓存中所有Long
键的getKeys()
方法。关于我哪里出了问题的任何想法?
使用泛型:
class UserCacheLoader extends CacheLoader<Long, User> {
@Override
public User load(Long key) throws Exception {
// ???
}
}
store(User)
可以使用 Cache.put
实现,就像您所期望的那样。
getKeys()
可以通过cache.asMap().keySet()
来实现。
您不仅可以(并且应该!)将 CacheLoader 的覆盖加载方法的返回类型指定为 User,还可以将 onRemove 方法参数指定为:
class UserCacheRemovalListener implements RemovalListener<String, String>{
@Override
public void onRemoval(RemovalNotification<Long, User> notification) {
// ...
}
}