GuavaCache使用

作者: 离别刀 | 来源:发表于2019-07-04 09:50 被阅读0次

依赖jar

<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>20.0</version>
</dependency>

工具类


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<String, Object> cache=null;
    @PostConstruct
    private void init(){
        cache = CacheBuilder.newBuilder()
                .maximumSize(5000) // 设置缓存的最大容量
                .expireAfterWrite(10, TimeUnit.MINUTES) // 设置缓存在写入一分钟后失效
                .concurrencyLevel(10) // 设置并发级别为10
                .recordStats() // 开启缓存统计
                .build();
    }
    public <T> T get(String key,Supplier<T> 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使用

    本文链接:https://www.haomeiwen.com/subject/xqtlhctx.html