为什么我的番石榴缓存会不断覆盖项目?

时间:2019-02-01 13:18:52

标签: java caching guava

与番石榴缓存大家好工作偶然发现这样的问题。我试图在其中有一些字段的CacheValue缓存番石榴中实现存储。余由基于LoadingCache番石榴缓存和I不明白为什么当我添加尺寸()元素它始终是1?

我的番石榴放置方法:

private LoadingCache<String, CacheValue> storage;
private static final Logger LOG = Logger.getLogger(GuavaCache.class);

@Override
public void put(String key, Object value) {
    storage.put(key, (CacheValue) value);
    storage = CacheBuilder.newBuilder()
            .expireAfterAccess(5, TimeUnit.SECONDS)
            .maximumSize(MAX_SIZE)
            .removalListener(notification -> LOG.info("Element was remove: " + notification.getKey()))
            .build(new CacheLoader<String, CacheValue>() {
                @Override
                public CacheValue load(String key) {
                    return (CacheValue) value;
                }
            });
}

我的主班:

   AbstractCustomCache gg = new GuavaCache();


    for (int i = 0; i < 102; i++) {
        gg.put("ab" + i, new CacheValue("ab" + i, System.currentTimeMillis(), 0));
    }

    gg.get("ab4");
    gg.get("ab2");
    gg.get("ab0");

我的输出:

CacheValue{value=ab0, creationDate=1549027075333, frequency=0}  Size=  1
CacheValue{value=ab1, creationDate=1549027075333, frequency=0}  Size=  1
CacheValue{value=ab2, creationDate=1549027075333, frequency=0}  Size=  1
CacheValue{value=ab3, creationDate=1549027075334, frequency=0}  Size=  1
CacheValue{value=ab4, creationDate=1549027075334, frequency=0}  Size=  1
CacheValue{value=ab5, creationDate=1549027075334, frequency=0}  Size=  1
CacheValue{value=ab6, creationDate=1549027075334, frequency=0}  Size=  1
CacheValue{value=ab7, creationDate=1549027075334, frequency=0}  Size=  1
CacheValue{value=ab8, creationDate=1549027075334, frequency=0}  Size=  1
CacheValue{value=ab9, creationDate=1549027075334, frequency=0}  Size=  1

AbstractCustomCache:

public abstract class AbstractCustomCache implements CustomCache {
    static final int MAX_SIZE = 8;
    private Map<String, CacheValue> storage = new ConcurrentHashMap<>();

    public Map<String, CacheValue> getStorage() {
        return storage;
    }

出什么问题了?如何解决?

1 个答案:

答案 0 :(得分:2)

您正在创建storage = CacheBuilder.newBuilder()与放request.You每次应该创建一次。

storage = CacheBuilder.newBuilder()
            .expireAfterAccess(5, TimeUnit.SECONDS)
            .maximumSize(MAX_SIZE)
            .removalListener(notification -> LOG.info("Element was remove: " + notification.getKey()))
            .build(new CacheLoader<String, CacheValue>() {
                @Override
                public CacheValue load(String key) {
                    return (CacheValue) value;
                }
            });

以上应在初始化缓存中调用一次。 那么,什么是实际发生的情况是,每PUT请求创建新的存储和“cacheValue”在任何时候加入到it.Therefore时间最大条目数为1。