guava cache 缓存

1.guava缓存

新建一个缓存对象cache,当取不到key对应的值时,生成一个,并插入到cache中

LoadingCache<String,String> cache = CacheBuilder.newBuilder().expireAfterWrite(30,TimeUnit.MINUTES).build(new CacheLoader<String, String>() {
            @Override
            public String load(String s) throws Exception {
                // 查询,返回值
                return s + UUID.randomUUID();
            }
});

2.guava 添加数据

cache.put("world1","world1" + UUID.randomUUID());
System.out.println(cache.get("world1"));
cache.put("world1","world1" + UUID.randomUUID());
System.out.println(cache.get("world1"));
// 取数据的时候要用get,别用getIfPresent,是因为getIfPresent在取不到数据时,直接返回null,而不走自定义的cacheLoader,从库里读取数据
posted @ 2020-12-18 16:19  SpecialSpeculator  阅读(153)  评论(0)    收藏  举报