A little about the LoadingCache of guava

Original link: https://clclcl.fun/2020/03/28/java/LoadingCache-null-value/

Google's guava is a good project, provided such as collections, caching, concurrency, String tools and so on, there really is Java development tool. Here briefly about that precautions LoadingCache use. There ifeve.com translation cache related to the introduction, in here .

When using the Cache, our priority read cache, when the cache does not exist, from the actual acquisition of data storage, such as DB, disk, network, etc., that get-if-absent-compute. guava provides CacheLoader mechanism that allows us to automate this process by setting the Loader. Such as:

Cache<String, User> cache = CacheBuilder.newBuilder().expireAfterAccess(5, TimeUnit.MINUTES);
user = cache.get(name, () -> {
    User value = query(key);//from databse, disk, etc.
    return value;
});

Or use LoadingCache:

 LoadingCache<String, User> cache = CacheBuilder.newBuilder().expireAfterAccess(5, TimeUnit.MINUTES).build(
     new CacheLoader<String, User>() {
        @Override
        public User load(String name) throws Exception {
        User value = query(key);//from databse, disk, etc.
        return value;
        }
    }
);

This is comparable to a Map to write cached data to be much more convenient, but also can set the timeout expired automatically help us clean up the data.

But note that it is important, CacheLoader allowed to return data is NULL, otherwise it will throw an exception: CacheLoader returned null for key. So we need to ensure that data lookup must exist, or thrown outside of exception handling. In some cases, we may indeed not the data, such as user management module, before we add the data to the original query whether the user already exists, then it is also inappropriate when an exception is thrown, then you can use Optional to optimization CacheLoader:

 LoadingCache<String, Optional<User>> cache = CacheBuilder.newBuilder().expireAfterAccess(5, TimeUnit.MINUTES).build(
     new CacheLoader<String, Optional<User>>() {
        @Override
        public Optional<User> load(String name) throws Exception {
        User value = query(key);//from databse, disk, etc.
        return Optional.ofNullable(value);
        }
    }
);

In this way we ensure that the CacheLoader return value is not NULL, and business data exists only need to determine Optional.ifPresent () on the line, while other functions Optional in the business logic is also very useful.

Guess you like

Origin www.cnblogs.com/ofyou/p/guava-loading-cache.html