本地缓存GuavaCache的介绍及使用

一、GuavaCache的介绍


GuavaCache是一个本地缓存,有以下优点:

  1. 很好的封装了get、put操作,能够集成数据源。一般我们在业务中操作缓存都会操作缓存和数据源两部分。例如:put数据时,先插入DB 再删除原来的缓存,get数据时,先查缓存,命中则返回,没有命中时需要查询DB,再把查询结果放入缓存中。Guava封装了这么多步骤,只需要调用一次get/put方法即可。
  2. 它是线程安全的缓存,与ConcurrentMap相似,但前者增加了更多的元素失效策略,后者只能显示的移除元素。
  3. GuavaCache提供了三种基本的缓存回收方式:基于容量回收、定时回收和基于引用回收。定时回收有两种:按照写入时间,最早写入的最先回收;按照访问时间,最早访问的最早回收。
  4. 它可以监控加载/命中情况。

二、GuavaCache的使用


【测试代码01】

package mytest;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
/**
 *
 * @author bkp
 * @since 2020/10/20
 */
public class GuavaTest {
    public static void main(String[] args) {
        LoadingCache<String, Integer> cache = CacheBuilder.newBuilder()
                //最多存放十个数据
                .maximumSize(10)
                //缓存10秒,10秒之后进行回收
                .expireAfterWrite(10, TimeUnit.SECONDS)
                .recordStats()//开启,记录状态数据功能
                .build(new CacheLoader<String, Integer>() {
                    //数据加载,默认返回-1,也可以是查询操作,如从DB查询
                    @Override
                    public Integer load(String key) throws Exception {
                        // TODO Auto-generated method stub
                        return -1;
                    }
                });
        //只查询缓存,没有命中,即返回null
        System.out.println(cache.getIfPresent("key1"));
        //put数据,放在缓存中
        cache.put("key1", 1);
        //再次查询,已经存在缓存中
        System.out.println(cache.getIfPresent("key1"));
        try {
            //查询缓存,未命中,调用load方法,返回-1
            System.out.println(cache.get("key2"));
            //put数据,更新缓存
            cache.put("key2", 2);
            //查询得到最新的数据
            System.out.println(cache.get("key2"));
            System.out.println("size:" + cache.size());
            //插入十个数据
            for (int i = 3; i < 13; i++) {
                cache.put("key"+i, i);
            }
            //超过最大容量,删除最早插入的数据
            System.out.println("size:" + cache.size());
            System.out.println(cache.getIfPresent("key2"));
            //等待5秒
            Thread.sleep(5000);
            cache.put("key1", 1);
            cache.put("key2", 2);
            //key5没失效,key3、key4已经失效
            System.out.println(cache.getIfPresent("key5"));
            //等待5秒
            Thread.sleep(5000);
            //此时key5-key12已经失效,但是size没有更新
            System.out.println("size :" + cache.size());
            System.out.println(cache.getIfPresent("key1"));
            System.out.println("size :" + cache.size());
            //获取key5,发现已经失效,然后刷新缓存,遍历数据,去掉失效的所有数据
            System.out.println(cache.getIfPresent("key5"));
            //此时只有key1,key2没有失效
            System.out.println("size :" + cache.size());
            System.out.println("status, hitCount:" + cache.stats().hitCount()
                    + ", missCount:" + cache.stats().missCount());

            //等待5秒
            Thread.sleep(10000);
            System.out.println("size :" + cache.size());
            System.out.println(cache.getIfPresent("key1"));

        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

运行结果:

null
1
-1
2
size:2
size:10
null
5
size :10
1
size :10
null
size :2
status, hitCount:4, missCount:4
size :2
null

【测试代码02】

package mytest;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
/**
 *
 * @author xzw
 * @since 2020/10/20
 */
public class GuavaTest02 {
    public static Cache<String, String> caches = CacheBuilder.newBuilder().
            //设置容量上限
            maximumSize(128)
            //若3秒内没有读写请求则进行回收
            .expireAfterAccess(3, TimeUnit.SECONDS)
            .removalListener(new RemovalListener<String, String>() {
                //移除监听器
                @Override
                public void onRemoval(RemovalNotification<String, String> notification) {
                    System.out.println(notification.getKey());
                }
            }).build();

    public static String get(final String key) throws Exception{
        String rr = caches.get(key, new Callable<String>() {

            @Override
            public String call() throws Exception {
                if ("1".equalsIgnoreCase(key)) {
                    return "test";
                }
                throw new Exception("This is a test!");
            }
        });
        return rr;
    }

    public static void main(String[] args) throws Exception {
        System.out.println(GuavaTest02.get("1"));
        System.out.println("before expire: " + GuavaTest02.caches.asMap().keySet());
        Thread.sleep(5000);
        System.out.println("after expire: " + GuavaTest02.caches.asMap().keySet());
    }
}

运行结果:

test
before expire: [1]
after expire: []

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值