场景:在开发过程中遇到一个问题,在连接redis的时候超时,spring.redis.timeout=1000设置了一秒超时,但是抛出redisconnectionfailureexception大约在10秒后,网上找了相关资料也没有找到什么原因,所以想着用代码去实现,这里用到了CompletableFuture。
Java8实现方式:
final String redisKey = key;
//redis连接超时10秒后才会报错,这里指定下超时时间为1500毫秒
String redisValue = CompletableFuture.supplyAsync(() -> {
return redisUtil.get(redisKey);
}).get(1500, TimeUnit.MILLISECONDS);
Java9两种实现方式:
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(this::computeEndlessly)
.orTimeout(1, TimeUnit.SECONDS);
//或者
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(this::computeEndlessly)
.completeOnTimeout(42, 1, TimeUnit.SECONDS);