如何使用Google Guava自动刷新缓存? [英] How to automatically refresh Cache using Google Guava?

查看:179
本文介绍了如何使用Google Guava自动刷新缓存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Google Guava库进行缓存。
对于自动缓存刷新,我们可以执行以下操作:

I am using Google Guava library for caching. For automatic cache refresh we can do as follows:

cache = CacheBuilder.newBuilder()               
                    .refreshAfterWrite(15, TimeUnit.MINUTES)
                    .maximumSize(100)
                    .build(....);

但是,当第一个条目的陈旧请求发生时执行自动刷新

However, automatic refreshes are performed when the first stale request for an entry occurs.

有没有办法自动刷新它,即使没有缓存数据的请求?像每15分钟一样,缓存数据应该无论是否有人调用缓存数据,都可以从Db中提取并加载它。

Is there a way to refresh it automatically even though no requests came for cache data? Like for every 15 minutes the cache data should be pulled from Db and load it, no matter whether anybody called cache data or not.

此外,Guava的缓存到期时间是针对整个缓存的。 是否可以根据密钥使缓存值到期?类似缓存数据,密钥NOT_SO_FREQ_CHANGE_DATA每1小时到期,密钥FREQ_CHANGING_DATA的数据每15分钟到期一次?

Also, Guava's cache expiry time is for entire cache. Is it possible to expire cache values based on key? Like cache data with key "NOT_SO_FREQ_CHANGE_DATA" to expire for every 1 hour and data with key "FREQ_CHANGING_DATA" should expire for every 15 minutes?

推荐答案

Guava无法批量刷新缓存,但您可以自行安排定期刷新:

Guava provides no way to refresh the cache in bulk, but you can schedule a periodic refresh yourself:

LoadingCache<K, V> cache = CacheBuilder.newBuilder()
        .refreshAfterWrite(15, TimeUnit.MINUTES)
        .maximumSize(100)
        .build(new MyCacheLoader());

for (K key : cache.asMap().keySet()) {
    cache.refresh(key);
}

但是在这种情况下你可能想要覆盖 CacheBuilder.reload(K,V) MyCacheLoader 中的方法,因此它以异步方式执行。

But in that case you may want to override the CacheBuilder.reload(K, V) method in MyCacheLoader so it performs asynchronously.

关于第二个问题,不,你不能在番石榴中设置每个条目的到期日期。

As for the second question, no, you cannot set a per-entry expiration in Guava.

这篇关于如何使用Google Guava自动刷新缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆