Click here to Skip to main content
16,004,806 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi friends:

i use java Google Guava cache to do localcache. but, i met a very strange appearance.

it is not produced when i use console program. but, it is produced in my web project.

the strange matter is that guava cannot get key-value cache by get(key), but reload a initialization code to save key-value data, then return value, i can see them to be save in cache by debug. I don't know why get method cannot find out the key.

In advance, thanks for you!

BR,
Bo


What I have tried:

Java
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.sankuai.meishi.qa.apm.thrift.ApmFilterItems;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@Component
public class GuavaCachManager {

    private static LoadingCache<String, List<ApmFilterItems>> objectCache = null;

    private static Object locker = new Object();

    //loadingCache
    public LoadingCacheObject createLoadingCacheObject(long span, TimeUnit timeUnit, CacheLoader<String, List<ApmFilterItems>> cacheLoader) {
        if (objectCache == null) {
            synchronized (locker) {
                if (objectCache != null) {
                    return new LoadingCacheObject(objectCache);
                }
          
                LoadingCache<String, List<ApmFilterItems>> loadingCache = CacheBuilder.newBuilder().expireAfterAccess(span, timeUnit).
expireAfterWrite(span, timeUnit).
 refreshAfterWrite(span, timeUnit).
 weakKeys().
maximumSize(3).build(cacheLoader);

                objectCache = loadingCache;
            }

        }

        return new LoadingCacheObject(objectCache);
    }

    public class LoadingCacheObject {

        private  LoadingCache<String, List<ApmFilterItems>> loadingCache;

        public  LoadingCacheObject(LoadingCache<String, List<ApmFilterItems>> cache) {
            loadingCache = cache;
        }

      public List<ApmFilterItems> get(String key) {
            try {
                return loadingCache.get(key);
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            return null;
        }

        public List<ApmFilterItems> getIfPresent(String key)
        {
            return loadingCache.getIfPresent(key);
        }
    }
}
Posted
Updated 13-Sep-18 1:57am
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900