我想讓番石榴緩存爲我的應用程序工作。具體來說,我基本上尋找其行爲類似地圖緩存:番石榴緩存爲自定義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()
方法,該方法返回緩存中的所有密鑰。任何想法,我要去哪裏錯誤?