简体   繁体   English

如何配置番石榴缓存以读取后删除项目?

[英]How to configure guava cache to remove item after a read?

I would like to remove (invalidate) an item after it was read from a cache. 我想从缓存中读取一项后将其删除(使之无效)。

So item should be present in a cache until a first read. 因此,项应该存在于缓存中,直到第一次读取。

I've tried adding expireAfterAccess(0, TimeUnit.NANOSECONDS) but then cache is not populated. 我尝试添加expireAfterAccess(0, TimeUnit.NANOSECONDS)但是未填充缓存。

Is there any way to use guava cache in such manner or do I need to invalidate item manually after a read? 有什么办法可以以这种方式使用番石榴缓存,还是需要在读取后手动使项目无效?

This won't work. 这行不通。 "Access" means "read or write access" and when it expires immediately after read, then it also expires immediately after write. “访问”是指“读或写访问”,当它在读取后立即失效时,则在写后也立即终止。

You can remove the entry manually. 您可以手动删除条目。 You can use the asMap() view in order to do it in a single access: 您可以使用asMap()视图来进行一次访问:

String getAndClear(String key) {
    String[] result = {null};    
    cache.asMap().compute(key, (k, v) ->
        result[0] = v;
        return null;
    });
    return result[0];
}

You could switch to Caffeine, which is sort of more advanced Guava cache and offers very flexible expireAfter(Expiry) . 您可以切换到Caffeine,它是一种更高级的Guava缓存,并提供了非常灵活的expireAfter(Expiry)

However, I don't think, that what you want is a job for a cache. 但是,我不认为您想要的是缓存工作。 As nonces should never be repeated, I can't imagine any reason to store them. 由于永远不应该重复随机数,因此我无法想象有任何理由来存储它们。 Usually, you generate and use them immediately. 通常,您会立即生成并使用它们。

You may be doing it wrong and you may want to elaborate, so that a possible security problem gets avoided. 您可能做错了,可能需要详细说明,从而避免了可能的安全问题。

In my example nonce are created twice: 在我的示例中,nonce被创建两次:

LoadingCache<String, String> cache = CacheBuilder.newBuilder().expireAfterAccess(0, TimeUnit.NANOSECONDS)
    .build(new CacheLoader<String, String>() {
        @Override
        public String load(String key) throws Exception {
            return createNonce();
        }
    });

@Test
public void test_cache_eviction() throws Exception {
    String nonce1 = cache.getUnchecked("key");
    String nonce2 = cache.getUnchecked("key");
}

public String createNonce() {
    String createdNonce = "createdNonce";
    System.out.println(createdNonce);
    return createdNonce;
}

In logs "createdNonce" are printed twice. 在日志中,“ createdNonce”被打印两次。

get和remove操作是在map界面上的简单remove

 Object cachedValue = cache.asMap().remove(key);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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