2014-11-21 76 views
0

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

回答

1

使用泛型:

class UserCacheLoader extends CacheLoader<Long, User> { 
    @Override 
    public User load(Long key) throws Exception { 
     // ??? 
    } 
} 

store(User)可以Cache.put來實現,就像你所期望的。

getKeys()可以用cache.asMap().keySet()實現。

0

你可以(而且應該!)不僅指定的CacheLoader的被覆蓋的負載方法的返回類型爲用戶也是onRemoval方法的參數是:

class UserCacheRemovalListener implements RemovalListener<String, String>{ 
@Override 
public void onRemoval(RemovalNotification<Long, User> notification) { 
    // ... 
} 

}