• Guava Cache CRUD


    原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/14993185.html

    简单介绍

    Guava 是Google 提供的一套Java 工具包,而Guava Cache 是一种非常优秀的本地缓存解决方案,提供了基于容量、时间和引用的缓存回收方式。
    相对于Redis,减少了频繁的网络I/O,速度快,效率高。

    使用场景

    愿意消耗一些内存空间来提升速度
    预计某些key 会被多次查询
    缓存中存放的数据总量不会超过内存容量

    构建方式 

    使用说明

    Guava Cache 缓存有两种加载方式,利用CacheBuilder 的 builder 模式构建:

    • CacheLoader 是按key 统一加载,所有取不到数据,则统一执行一种load 逻辑
    • Callable 方法允许在get 的时候指定 key

    构建步骤

    1. 设置缓存容量
    2. 设置超时时间
    3. 提供移除监听器
    4. 提供缓存加载器
    5. 构建缓存

    Demo

    Maven Dependency

    <dependencies>
        ...
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>30.1.1-jre</version>
        </dependency>
         ...
    </dependencies>

    SRC

    package org.fool.cache;
    
    import com.google.common.cache.CacheBuilder;
    import com.google.common.cache.CacheLoader;
    import com.google.common.cache.LoadingCache;
    import com.google.common.cache.RemovalListener;
    import com.google.common.cache.RemovalNotification;
    import lombok.extern.slf4j.Slf4j;
    
    import java.util.concurrent.ConcurrentMap;
    import java.util.concurrent.TimeUnit;
    
    @Slf4j
    public class GuavaCacheService {
        private static final LoadingCache<String, String> CACHE = CacheBuilder.newBuilder()
                //设置大小,条目数
                .maximumSize(20)
                //设置时效时间,最后一次被访问后
                .expireAfterAccess(5, TimeUnit.SECONDS)
                //移除缓存的监听器
                .removalListener(new RemovalListener<String, String>() {
                    @Override
                    public void onRemoval(RemovalNotification<String, String> notification) {
                        log.info("removing cache: {{}:{}}", notification.getKey(), notification.getValue());
                    }
                })
                .build(new CacheLoader<String, String>() {
                    //缓存构建的回调
                    //加载缓存
                    @Override
                    public String load(String key) throws Exception {
                        log.info("loading cache with key: {}", key);
                        return "test" + "_" + key;
                    }
                });
    
        /**
         * 获取缓存值
         * 注:如果键不存在值,将调用CacheLoader的load方法加载新值到该键中
         */
        public static String get(String key) {
            try {
                String value = CACHE.get(key);
                log.info("get cache with key: {}, value: {}", key, value);
                return value;
            } catch (Exception e) {
                log.error("get cache data error with key: {}", key, e);
            }
            return null;
        }
    
        /**
         * 移除缓存
         */
        public static void remove(String key) {
            try {
                log.info("remove cache with key: {}", key);
                CACHE.invalidate(key);
            } catch (Exception e) {
                log.error("remove cache data error with key: {}", key, e);
            }
        }
    
        /**
         * 清空缓存内数据
         * 操作基础数据时,清除重新查询
         */
        public static void removeAll() {
            log.info("remove all cache");
            CACHE.invalidateAll();
        }
    
        /**
         * 设置缓存值
         * 注: 若已有该key值,则会先移除(会触发removalListener移除监听器),再添加
         */
        public static void add(String key, String value) {
            CACHE.put(key, value);
            log.info("add cache with key: {}, value: {}", key, value);
        }
    
        /**
         * 查看缓存中内容
         */
        public static ConcurrentMap<String, String> getAll() {
            log.info("get all cache: {}", CACHE.asMap());
            return CACHE.asMap();
        }
    
        public static void main(String[] args) throws Exception {
            add("abc", "abcval");
            get("abc");
            add("abc", "xyzval");
            get("abc");
            getAll();
    
            System.out.println("===start sleep===");
            Thread.sleep(10000);
            System.out.println("===end sleep===");
            getAll();
    
            get("cache1");
            get("cache2");
            getAll();
    
            remove("cache2");
            getAll();
    
            removeAll();
            getAll();
        }
    }

    Console Output

    Reference

    https://time.geekbang.org/course/detail/100051101-235861

    https://time.geekbang.org/course/detail/100051101-235864


    欢迎点赞关注和收藏

    强者自救 圣者渡人
  • 相关阅读:
    JS兼容性总结
    [妙味DOM]第五课:事件深入应用
    关于iOS开发的学习
    世界经典——乔布斯
    梦想改变世界
    乔布斯在斯坦福大学的演讲
    10步让你成为更优秀的程序员
    程序员的八个级别
    程序员的学习和积累
    哈佛大学二十条训言
  • 原文地址:https://www.cnblogs.com/agilestyle/p/14993185.html
Copyright © 2020-2023  润新知