缓存初见——Guava Cache的简单使用

本文介绍了Guava Cache的基础知识,包括Guava Cache的简介,详细阐述了两种使用方式:通过CacheLoader和Callable进行加载,并探讨了Guava Cache的回收策略。
摘要由CSDN通过智能技术生成

Guava Cache简介

在这里插入图片描述

Guava Cache使用的几种方式

在这里插入图片描述

1、使用CacheLoader加载

public static void main(String[] args) {
        // 缓存加载器
        CacheLoader<String, String> loader = new CacheLoader<String, String>() {
            @Override
            public String load(String s) throws Exception {
                Thread.sleep(1000);

                System.out.println(s + " loaded from cache loader.");
                return s + "的值";
            }
        };

        // 数据移除监听器
        RemovalListener<String, String> listener = new RemovalListener<String, String>() {
            @Override
            public void onRemoval(RemovalNotification<String, String> removal) {
                System.out.println(removal.getKey() + "=" + removal.getValue() + " was evicted...");
            }
        };

        LoadingCache<String, String> cache = CacheBuilder.newBuilder()
                // 缓存容量为5
                .maximumSize(5)
                // 移除元素监听器
                .removalListener(listener)
                // 超时机制
                .expireAfterWrite(10, TimeUnit.MINUTES)
                .expireAfterAccess(10, TimeUnit.MINUTES)
                // 设置缓存加载器
                .build(loader);

        for (int i = 0; i < 10; i++) {
            cache.put("key"+i, "value"+i);
            System.out.println("key"+i + "=" + "value"+i + "was put into cache");
        }

        // 获取元素,不存在则返回null
        System.out.println(cache.getIfPresent("key"));

        // 获取元素,不存在则通过cacheLoader.load()加载
        try {
            System.out.println(cache.get("key777"));
        } catch (ExecutionException e) {
            System.out.println("key 不存在");
        }

    }

2、使用Callable加载

public static void main(String[] args) {
        Cache<String, String> cache = CacheBuilder.newBuilder()
                .maximumSize(5)
                .build();

        cache.put("key666", "value666");

        // 不存在,则返回null
        System.out.println(cache.getIfPresent("key333"));

        try {
            // 存在就返回,不存在则调用call()方法,将返回值缓存、返回
            System.out.println(cache.get("key333", new Callable<String>() {
                @Override
                public String call() throws Exception {
                    return "运算、缓存、返回";
                }
            }));
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

Guava Cache回收策略

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值