import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListenableFutureTask;
import java.time.Duration;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* 对于一些数据查询比较耗时,缓解服务器的压力,高并发的场景下,可以使用refreshAfterWrites这种异步刷新缓存的方法。
* 问题:
* 1、会不会出现取到的值是过期的旧值?
* 2、随着请求的快速上升,连接数是否足够?
*
* LoadingCache 之 refreshAfterWrites 刷新机制
* 把数据加入到缓存中,并异步刷新缓存里的数据
*
*/
public class Test03 {
public LoadingCache<String, Long> cache;
private static ExecutorService executorService = Executors.newFixedThreadPool(300);
private Long getByKey(String key) {
return System.currentTimeMillis();
}
/**
* 构建缓存对象
*/
private void buildCache() {
cache = CacheBuilder.newBuilder().expireAfterWrite(Duration.ofSeconds(10)).refreshAfterWrite(8, TimeUnit.SECONDS)
.build(new CacheLoader<String, Long>() {
@Override
public Long load(String s) throws Exception {
Long result = getByKey(s);
System.out.println("------------------------------------load ... s:" + s + " 时间:" + System.currentTimeMillis());
return result;
}
@Override
public ListenableFuture<Long> reload(String key,Long oldValue) throws Exception {
System.out.println("----------------------------------- reload ... key:" + key + " oldValue:" + oldValue + " 时间:" + System.currentTimeMillis());
ListenableFutureTask<Long> task = ListenableFutureTask
.create(new Callable<Long>() {
@Override
public Long call() throws Exception {
String key1 = key;
return getByKey(key1);
}
});
executorService.execute(task);
return task;
}
});
}
/**
* 测试
*/
public static void main(String[] args) throws Exception {
Test03 demo = new Test03();
demo.buildCache();
int i000=0;
System.out.println("开始时间:" + System.currentTimeMillis());
for(int i=0; i<100; i++) {
System.out.println("xxxx 01------------------- " + demo.cache.get("test_01"));
Thread.sleep(3*1000);
}
}
}
Cache Guava refreshAfterWrite主动刷新缓存
最新推荐文章于 2024-05-08 09:18:42 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)