简体   繁体   中英

Guava cache for custom POJO

I am trying to get Guava Caching working for my app. Specifically, I'm basically looking for a cache that behaves like a map:

// Here the keys are the User.getId() and the values are the respective User.
Map<Long, User> userCache = new HashMap<Long, User>();

From various online sources (docs, blogs, articles, etc.):

// 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.");
    }
}

But I'm not sure how/where to specify that keys should be Long types, and cached values should be User instances. I'm also looking to implement a store(User) (basically a Map#put(K,V) ) method as well as a getKeys() method that returns all the Long keys in the cache. Any ideas as to where I'm going awry?

Use generics:

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

store(User) can be implemented with Cache.put , just like you'd expect.

getKeys() can be implemented with cache.asMap().keySet() .

You can (and should!) not only specify the return type of the overriden load method of CacheLoader to be User but also the onRemoval method argument to be:

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM