Guava cache简单使用

使用guava cache用来构建内存级别的缓存,减少对数据库的访问次数

public class Test {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        LoadingCache cahceBuilder = CacheBuilder
                .newBuilder()
                .maximumSize(1)  //容量
                .expireAfterWrite(1, TimeUnit.SECONDS)  //多久过期
                .build(new CacheLoader() {
                    @Override
                    public String load(String key) throws Exception {
                        return sssss(key);
                    }
                });
        System.out.println("jerry value:" + cahceBuilder.get("jerry"));
        Thread.sleep(1500); //设置1.5s过期,这时候会触发重新取
        System.out.println("jerry value:" + cahceBuilder.get("jerry"));
    }

    private static String sssss(String key) {
        System.out.println("load " + key);
        String strProValue = "hello " + key + "!";
        return strProValue;
    }
}

打印

load jerry
jerry value:hello jerry!
load jerry
jerry value:hello jerry!


你可能感兴趣的:(Java工具类)