Guava Cache
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>30.1-jre</version>
</dependency>
import com.google.common.cache.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class LocalCache {
public static void main(String[] args) throws ExecutionException {
LoadingCache<String,Object> loadingCache
= (LoadingCache<String, Object>) CacheBuilder.newBuilder()
.concurrencyLevel(8)
.expireAfterWrite(8, TimeUnit.SECONDS)
.refreshAfterWrite(1,TimeUnit.SECONDS)
.initialCapacity(10)
.maximumSize(100)
.recordStats()
.removalListener(new RemovalListener<String, Object>() {
@Override
public void onRemoval(RemovalNotification<String, Object> removalNotification) {
System.out.println(removalNotification.getKey() + "被移除,原因:" + removalNotification.getCause());
}
}).build(
new CacheLoader<String, Object>() {
@Override
public Object load(String key) throws Exception {
System.out.println("缓存不存在时,从数据加载"+key);
return new Object();
}
}
);
for (int i = 0; i < 20; i++) {
Object o = loadingCache.get(i + "");
System.out.println(o);
}
for (int i = 0; i < 20; i++) {
Object o = loadingCache.get(i + "");
System.out.println(o);
}
System.out.println("缓存命中率:"+loadingCache.stats());
}
}