Guava loadingCache工具

比较好用的Guava缓存工具。

 

package com.cloudwise.util;


import com.google.common.cache.*;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program
 * @description: LoadingCache Utils for K-V store
 * @author: back
 * @create: 2019/08/08 11:00
 */
@Slf4j
public class GuavaCacheUtils {


    public final static Integer GUAVA_CACHE_SIZE = 500;
    //缓存 存活时间 5分钟
    public final static Integer GUAVA_CACHE_SECOND = 60 * 5;



    private static LoadingCache loadCache(CacheLoader cacheLoader) throws Exception {

        LoadingCache cache = CacheBuilder.newBuilder()
                //缓存池大小,在缓存项接近该大小时, Guava开始回收旧的缓存项
                .maximumSize(GUAVA_CACHE_SIZE)
                //设置时间对象没有被读/写访问则对象从内存中删除(在另外的线程里面不定期维护)
                .expireAfterAccess(GUAVA_CACHE_SECOND, TimeUnit.SECONDS)
                // 设置缓存在写入之后 设定时间 后失效
                .expireAfterWrite(GUAVA_CACHE_SECOND, TimeUnit.SECONDS)
                //移除监听器,缓存项被移除时会触发
                .removalListener(new RemovalListener() {
                    @Override
                    public void onRemoval(RemovalNotification rn) {
                        //逻辑操作
                    }
                })
                //开启Guava Cache的统计功能
                .recordStats()
                .build(cacheLoader);
        return cache;
    }

    private volatile static LoadingCache cache = getCache();

    private static LoadingCache getCache() {

        if (null == cache) {
            synchronized (GuavaCacheUtils.class) {
                if (cache == null) {
                    try {
                        cache  = loadCache(new CacheLoader() {
                            @Override
                            public String load(String key) throws Exception {
                                // 处理缓存键不存在缓存值时的处理逻辑
                                return "";
                            }
                        });
                    } catch (Exception e) {
                        log.error("Guava Cache Init Exception !");
                        e.printStackTrace();
                    }
                }
            }
        }
        return cache;
    }


    public static void put(String key, String value){
        cache.put(key,value);
    }

    public static String get(String key){
        String s = null;
        try {
            s = cache.get(key);
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return s;
    }

    public static void remove(String key){
        cache.invalidate(key);
    }

    private GuavaCacheUtils() throws Exception {
        throw new Exception("lalal");
    }


    /**
     * test class Sucessful!
     * @param args
     */
    public static void main(String[] args) {


    }
}

 

你可能感兴趣的:(工具)