GuavaCache使用

依赖jar



    com.google.guava
    guava
    20.0

工具类


import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 * Created by Administrator on 2019-4-16 0016.
 */
@Component
public class GuavaCacheComponent {
    private Cache cache=null;
    @PostConstruct
    private void init(){
        cache = CacheBuilder.newBuilder()
                .maximumSize(5000) // 设置缓存的最大容量
                .expireAfterWrite(10, TimeUnit.MINUTES) // 设置缓存在写入一分钟后失效
                .concurrencyLevel(10) // 设置并发级别为10
                .recordStats() // 开启缓存统计
                .build();
    }
    public  T get(String key,Supplier dbFunc){
        Object obj= cache.getIfPresent(key);
        if(obj!=null){
            return (T) obj;
        }
        T  ob= dbFunc.get();
        put(key,ob);
        return ob;
    }
    private void put(String key,Object val){
        if(val!=null){
            cache.put(key,val);
        }
    }

}

你可能感兴趣的:(GuavaCache使用)