简体   繁体   English

在Guava中过期后如何刷新缓存中的键和值(春季)

[英]How to refresh the key and value in cache after they are expired in Guava (Spring)

So, I was looking at caching methods in Java (Spring). 因此,我正在研究Java(春季)中的缓存方法。 And Guava looked like it would solve the purpose. 番石榴看起来可以解决目的。

This is the usecase - 这是用例-

I query for some data from a remote service. 我从远程服务查询一些数据。 Kind of configuration field for my application. 我的应用程序的配置字段类型。 This field will be used by every inbound request to my application. 我的应用程序的每个入站请求都将使用此字段。 And it would be expensive to call the remote service everytime as it's kind of constant which changes periodically. 每次都调用远程服务会很昂贵,因为它是一个不断变化的常量。

So, on the first request inbound to my application, when I call remote service, I would cache the value. 因此,在第一个入站到我的应用程序的请求上,当我调用远程服务时,我将缓存该值。 I set an expiry time of this cache as 30 mins. 我将此缓存的到期时间设置为30分钟。 After 30 mins when the cache is expired and there is a request to retrieve the key, I would like a callback or something to do the operation of calling the remote service and setting the cache and return the value for that key. 30分钟后,当缓存过期并且有一个请求检索密钥的请求后,我希望进行回调或其他操作来调用远程服务并设置缓存并返回该密钥的值。

How can I do it in Guava cache? 如何在Guava缓存中执行此操作?

Here i give a example how to use guava cache. 在这里我举一个例子,如何使用番石榴缓存。 If you want to handle removal listener then need to call cleanUp . 如果要处理removal listener则需要调用cleanUp Here i run a thread which one call clean up every 30 minutes. 我在这里运行一个线程,每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);
        }
    });
}
}

put & get data: 放置和获取数据:

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

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

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