Google Guava学习 -Guava cache

谷歌Guava缓存

Guava介绍

Guava是Google guava中的一个内存缓存模块,用于将数据缓存到JVM内存中。实际项目开发中经常将一些公共或者常用的数据缓存起来方便快速访问。

Guava Cache是单个应用运行时的本地缓存。它不把数据存放到文件或外部服务器。如果不符合需求,可以选择Memcached、Redis等工具。

@Component
public class LocalCache {

    private Cache<String,Object> localCache=null;

    @PostConstruct
    private void init(){
        //CacheBuilder的构造函数是私有的,只能通过其静态方法newBuilder()来获得CacheBuilder的实例
        localCache= CacheBuilder.newBuilder()
                //设置并发级别为8,并发级别是指可以同时写缓存的线程数
                .concurrencyLevel(8)
                //设置写缓存后8秒钟过期
                .expireAfterWrite(8, TimeUnit.SECONDS)
                //设置缓存容器的初始容量为5
                .initialCapacity(5)
                //设置缓存最大容量为100,超过100之后就会按照LRU最近虽少使用算法来移除缓存项
                .maximumSize(100)
                //设置要统计缓存的命中率
                .recordStats()
                //设置缓存的移除通知
                .removalListener(new RemovalListener<Object, Object>() {
                    @Override
                    public void onRemoval(RemovalNotification<Object, Object> notification) {
                        System.out.println(notification.getKey() + " 被移除了,原因: " + notification.getCause());
                    }
                })
                .build();
                //设置写缓存后1秒钟刷新
//                .refreshAfterWrite(1, TimeUnit.SECONDS)
                build方法中可以指定CacheLoader,在缓存不存在时通过CacheLoader的实现自动加载缓存
//                .build(
//                        new CacheLoader<String, Object>() {
//                            @Override
//                            public Object load(String key) throws Exception {
//                                System.out.println("缓存没有时,从数据库加载" + key);
//                                return "数据库查出的key";
//                            }
//                        }
//                );
    }

    public void put(String key,Object value){
        localCache.put(key,value);
    }

    public Object get(String key){
        return localCache.getIfPresent(key);
    }

    public static void main(String[] args) throws Exception {
        LocalCache cache=new LocalCache();
        cache.init();
        cache.put("test","123");
        System.out.println(cache.get("test"));
        Thread.sleep(10000);
        System.out.println(cache.get("test"));
    }
}
经验分享 程序员 微信小程序 职场和发展