【问题标题】:How to refresh the key and value in cache after they are expired in Guava (Spring)Guava(Spring)中过期后如何刷新缓存中的键和值
【发布时间】:2018-07-27 13:10:32
【问题描述】:

所以,我正在研究 Java (Spring) 中的缓存方法。番石榴看起来可以解决这个问题。

这是用例 -

我从远程服务查询一些数据。我的应用程序的配置字段类型。我的应用程序的每个入站请求都将使用此字段。而且每次调用远程服务都会很昂贵,因为它是一种定期更改的常量。

因此,在我的应用程序的第一个入站请求中,当我调用远程服务时,我会缓存该值。我将此缓存的到期时间设置为 30 分钟。 30分钟后缓存过期并且有检索密钥的请求,我想要一个回调或其他东西来执行调用远程服务并设置缓存并返回该键的值的操作。

如何在 Guava 缓存中做到这一点?

【问题讨论】:

    标签: spring spring-mvc spring-boot guava google-guava-cache


    【解决方案1】:

    这里我举一个例子如何使用番石榴缓存。如果您想处理removal listener,则需要致电cleanUp。在这里,我运行一个线程,每 30 分钟清理一次。

    import com.google.common.cache.*;
    import org.springframework.stereotype.Component;
    
    
    import java.util.concurrent.Executors;
    import java.util.concurrent.TimeUnit;
    
    @Component
    public class Cache {
    
    public static LoadingCache<String, String> REQUIRED_CACHE;
    
    public Cache(){
        RemovalListener<String,String> REMOVAL_LISTENER = new RemovalListener<String, String>() {
            @Override
            public void onRemoval(RemovalNotification<String, String> notification) {
                if(notification.getCause() == RemovalCause.EXPIRED){
                    //do as per your requirement
                }
            }
        };
    
        CacheLoader<String,String> LOADER = new CacheLoader<String, String>() {
            @Override
            public String load(String key) throws Exception {
                return null; // return as per your requirement. if key value is not found
            }
        };
    
        REQUIRED_CACHE = CacheBuilder.newBuilder().maximumSize(100000000)
                .expireAfterWrite(30, TimeUnit.MINUTES)
                .removalListener(REMOVAL_LISTENER)
                .build(LOADER);
    
        Executors.newSingleThreadExecutor().submit(()->{
            while (true) {
                REQUIRED_CACHE.cleanUp(); // need to call clean up for removal listener
                TimeUnit.MINUTES.sleep(30L);
            }
        });
    }
    }
    

    放置和获取数据:

    Cache.REQUIRED_CACHE.get("key");
    Cache.REQUIRED_CACHE.put("key","value");
    

    【讨论】:

    • 所以,理想情况下,我只想获取缓存。在类 Cache 中的某个地方,是否有任何功能可以实现我的方法,在该方法中获取缓存,然后将缓存放在那里。
    • 这里我举例说明如何使用番石榴缓存
    • 如果你想处理删除监听器,那么我将展示如何处理它
    • 是的。是否可以将其扩展到我只需调用Cache.REQUIRED_CACHE.get("key"); 的用例。如果此键尚未在缓存中设置,它会在 Cache 类中设置?
    • 然后你可以在加载方法中设置key并返回
    猜你喜欢
    • 1970-01-01
    • 2013-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-01
    • 2013-09-14
    相关资源
    最近更新 更多