How to automatically refresh Cache using Google Guava?

前端 未结 5 1538
滥情空心
滥情空心 2020-12-23 20:39

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

cache = CacheBuilder.newBuilder()               
                      


        
5条回答
  •  被撕碎了的回忆
    2020-12-23 21:03

    Here is some sample code to refresh a cache. Guava cache is easy to implement and also it is fast.

    import java.util.concurrent.ExecutionException
    import java.util.concurrent.TimeUnit;
    
    import com.google.common.cache.CacheBuilder;
    import com.google.common.cache.CacheLoader;
    import com.google.common.cache.LoadingCache;
    
    public class GuavaTest {
        private static GuavaTest INSTANCE = new GuavaTest();
    
        public static GuavaTest getInstance(){
            return INSTANCE;
        }   
    
        private LoadingCache cache;
    
        private GuavaTest() {
            cache = CacheBuilder.newBuilder()
                    .refreshAfterWrite(2,TimeUnit.SECONDS)
                    .build(new CacheLoader() {
                            @Override
                            public String load(String arg0) throws Exception {
                                return addCache(arg0);
                            }
                    });
        }
    
        private String addCache(String arg0) {
            System.out.println("Adding Cache");
            return arg0.toUpperCase();
        }
    
        public String getEntry(String args) throws ExecutionException{
            System.out.println(cache.size());
            return cache.get(args);
        }
    
        public static void main(String[] args) {
            GuavaTest gt = GuavaTest.getInstance();
            try {
                System.out.println(gt.getEntry("java"));
                System.out.println(gt.getEntry("java"));
                Thread.sleep(2100);
                System.out.println(gt.getEntry("java"));
                System.out.println(gt.getEntry("java"));
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    }
    

    I referred this article guava cache example

提交回复
热议问题