代码之家  ›  专栏  ›  技术社区  ›  nirvair

如何在guava(spring)中刷新缓存中的键和值。

  •  0
  • nirvair  · 技术社区  · 7 年前

    所以,我正在研究Java(Spring)中的缓存方法。而番石榴似乎能解决这个问题。

    这是用例-

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

    因此,当我调用远程服务时,当第一个请求进入到我的应用程序时,我将缓存该值。我将此缓存的到期时间设置为30分钟。30分钟后,当缓存过期并且有检索密钥的请求时,我希望回调或执行调用远程服务并设置缓存并返回该密钥的值的操作。

    我怎么能在瓜娃的缓存里做呢?

    1 回复  |  直到 7 年前
        1
  •  2
  •   GolamMazid Sajib    7 年前

    removal listener cleanUp

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