缓存之Guava Cache示例

相信大家都有用过本地缓存的经历,很多时候我们用ConcurrentHashMap来作为缓存,但是ConcurrentHashMap毕竟是个Map,而不是专门的缓存,像缓存自动失效、缓存淘汰策略、缓存的加载并发问题等ConcurrentHashMap都没有提供相应的功能,需要自己改造。

下面就给大家介绍一款小而精的本地缓存Guava Cache,他是Google Guava工具包的一个模块。

    <dependencies>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>24.1-android</version>
        </dependency>
    </dependencies>
public class MainTest {

    public static void main(String[] args) throws Exception {

        LoadingCache<String, String> objectCache = CacheBuilder.newBuilder()
                //同时写缓存的线程数
                .concurrencyLevel(8)
                //写入后多久缓存失效
                .expireAfterWrite(1, TimeUnit.SECONDS)
                //访问后多久缓存失效
                .expireAfterAccess(1, TimeUnit.SECONDS)
                //设置缓存容量
                .initialCapacity(10).maximumSize(100)
                //设置要统计缓存的命中率
                .recordStats()
                //设置缓存移除监听器
                .removalListener(removalNotification -> {
                    System.out.println(removalNotification.getKey() + " was removed, cause is :" + removalNotification.getCause());
                })
                .build(new CacheLoader<String, String>() {
                    @Override
                    public String load(String key) throws Exception {
                        System.out.println("load data:" + key);
                        String value = key + ":cache-value";
                        return value;
                    }
                })
//                .build()
                ;

        objectCache.put("tuyou", "tuyou");
        objectCache.put("yangrui", "yangrui");

        System.out.println(objectCache.get("tuyou"));

        Thread.sleep(2000);
        System.out.println(objectCache.get("tuyou"));

        objectCache.invalidate("tuyou"); //主动删除缓存
        System.out.println(objectCache.get("tuyou"));
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值