Guava Cache

参考:

  1. Google Guava之–cache

1. 说明

关于Google Guava的介绍,参考其他文章。在此,仅做最实用的方法。

缓存刷新机制选择哪种呢?
首先看一下三种基于时间的清理或刷新缓存数据的方式:
expireAfterAccess: 当缓存项在指定的时间段内没有被读或写就会被回收。
expireAfterWrite:当缓存项在指定的时间段内没有更新就会被回收。
refreshAfterWrite:当缓存项上一次更新操作之后的多久会被刷新。
参考:(https://blog.youkuaiyun.com/abc86319253/article/details/53020432 )

实战demo:

package cache;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class TestGuavaCache3 {
    private Cache<String, String> TEST_STRING_CACHE = CacheBuilder.newBuilder().maximumSize(200000).expireAfterWrite(5, TimeUnit.MINUTES).build();
    /**定义一个方法用于获取STRING值,注意,直接从定义的TEST_STRING_CACHE中获取即可,
     * 第一次会通过回调从数据库中获取,后续就从缓存
     */
    private String getValue(String key){
        try {
            return TEST_STRING_CACHE.get(key,()->{
                if(key.equals("1")){
                    System.out.println("first get v1");
                    return "v1";
                }
                if(key.equals("2")){
                    System.out.println("first get v2");
                    return "v2";
                }
                System.out.println("first get other");
                return "other";
            });
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return "error";
    }

    public static void main(String[] args) {
        TestGuavaCache3 t=new TestGuavaCache3();
        System.out.println(t.getValue("1")); //首次会使用回调
        System.out.println(t.getValue("1")); //第二次,不会使用回调
        System.out.println(t.getValue("2"));
        System.out.println(t.getValue("2"));
        System.out.println(t.getValue("3"));
        System.out.println(t.getValue("3"));
    }

}

结果:

first get v1
v1
v1
first get v2
v2
v2
first get other
other
other

Process finished with exit code 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值