SpringBoot缓存(一)----guava本地缓存

谷歌开源的工具库,其Cache来源于jdk7的ConcurrentHashMap(jdk8的ConcurrentHashMap引入了红黑树)。

少量的数据缓存可以直接使用包装类,List、hashmap等。

如果希望数据存储的空间是可控的,并且改变结果,使用这种方法是推荐的。

首先pom里引入google的guava包。

 <dependency>
         <groupId>com.google.guava</groupId>
         <artifactId>guava</artifactId>
         <version>23.0</version>
</dependency>

代码里有注释,不作更多说明

@Slf4j
public class GuavaCache1 {
    public static void main(String[] args) {
        LoadingCache<String, Integer> cache = CacheBuilder.newBuilder()
                .maximumSize(10)//最多存放10个数据
                .expireAfterWrite(10, TimeUnit.SECONDS)//缓存10s
                .recordStats()//开启记录数据功能
                .build(new CacheLoader<String, Integer>() {
                    @Override
                    public Integer load(String s) throws Exception {
                        //当数据不存在时使用get()返回-1
                        return -1;
                    }
                });
        log.info("{}", cache.getIfPresent("key1"));//null
        cache.put("key1", 1);
        log.info("{}", cache.getIfPresent("key1"));//1
        cache.invalidate("key1");
        log.info("{}", cache.getIfPresent("key1"));//null
        try {
            log.info("{}",cache.get("key2") );//-1
            cache.put("key2",2 );
            log.info("{}",cache.get("key2") );//2
            log.info("{}",cache.size() );//1
            for (int i = 3; i < 13; i++) {
                cache.put("key"+i,i );
            }
            log.info("{}",cache.size() );//10
            //最大缓存为10,计算过期时间,将时间最长的去掉
            log.info("{}",cache.getIfPresent("key2") );//null
            log.info("{}",cache.get("key2") );//-1
            //时间大于10s,缓存过期
            Thread.sleep(11000);
            log.info("{}",cache.getIfPresent("key5") );//null
            //针对读操作,一个缓存还没有被读取就失效了,低命中,缓存效果差命中次数,丢失次数
            log.info("{},{}",cache.stats().hitCount(),cache.stats().missCount() );//2,5
            //命中率 ,丢失率
            log.info("{},{}",cache.stats().hitRate(),cache.stats().missRate() );

        } catch (Exception e) {
            log.error("cache exception", e);
        }
    }
}

 

 

@Slf4j
public class GuavaCache2 {
    public static void main(String[] args) {
        Cache<String, Integer> cache = CacheBuilder.newBuilder()
                .maximumSize(10)//最多存放10个数据
                .expireAfterWrite(10, TimeUnit.SECONDS)//缓存10s
                .recordStats()//开启记录状态数据功能
                .build();
        log.info("{}", cache.getIfPresent("key1"));//null
        cache.put("key1", 1);
        log.info("{}", cache.getIfPresent("key1"));//1
        cache.invalidate("key1");
        log.info("{}", cache.getIfPresent("key1"));//null
        try {
            log.info("{}", cache.get("key2", new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    return -1;
                }
            }));//-1
            cache.put("key2", 2);
            log.info("{}", cache.get("key2", new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    return -1;
                }
            })); // 2
            log.info("{}", cache.size()); // 1

            for (int i = 3; i < 13; i++) {
                cache.put("key" + i, i);
            }
            log.info("{}", cache.size()); // 10

            log.info("{}", cache.getIfPresent("key2")); // null

            Thread.sleep(11000);
            log.info("{}", cache.get("key5", new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    return -1;
                }
            })); // -1
            log.info("{},{}", cache.stats().hitCount(), cache.stats().missCount());

            log.info("{},{}", cache.stats().hitRate(), cache.stats().missRate());


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

GuavaCache1 对get()方法返回-1,是统一配置的,而GuavaCache2每次get()都要配置一次,如果需要返回不同的值用GuavaCache2

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值