2014-11-21 69 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) { 
    // ... 
} 

}