Aaron Bo Ответов: 0

Почему guava loadingcache всегда перезагружается, но не получает ключ кэша-значение по get(key) как поступающий запрос


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


Что я уже пробовал:

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);
        }
    }
}

0 Ответов