我想让番石榴缓存为我的应用程序工作。具体来说,我基本上寻找其行为类似地图缓存:番石榴缓存为自定义POJO
// 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)
)方法以及getKeys()
方法,该方法返回缓存中的所有密钥。任何想法,我要去哪里错误?