依赖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);
}
}
}