private static AtomicBoolean refreshCaching = new AtomicBoolean(false);
private static LoadingCache<String, String> cache1 = CacheBuilder.newBuilder()
.maximumSize(1000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.removalListener((rn)->{log.info("remove:{}", rn);})
.build(new TestCache());
public static void main(String[] args) {
List<String> test1 = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
test1.add("zmm"+i);
}
for (String s : test1) {
try {
String result = getCache(s);
log.info("成功获取缓存key:{},value:{}", s, result);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
long l = System.currentTimeMillis();
ConcurrentMap<String, String> map = cache1.asMap();
boolean refreshing = refreshCaching.compareAndSet(false, true);
if (!refreshing){
map.keySet().forEach(item ->map.remove(item));
refreshCaching.set(false);
}else{
log.error("正在刷新,请等待");
}
long l1 = System.currentTimeMillis() - l;
log.info("刷新缓存耗时:{}", l1);
}
private static String getCache (String key)throws Exception{
while (true){
if (!refreshCaching.get()){
return cache1.get(key);
}
log.info("缓存刷新中,自旋等待");
Thread.sleep(100);
}
}
public static class TestCache extends CacheLoader<String, String> {
@Override
public String load(String key) throws Exception {
log.info("从数据库获取缓存:{}", key);
return "1";
}
}
标签:info,缓存,log,代码,static,key,刷新,String From: https://www.cnblogs.com/loveCrane/p/17792922.html