Retry logic with CompletableFuture

后端 未结 7 2144
别跟我提以往
别跟我提以往 2021-01-31 18:26

I need to submit a task in an async framework I\'m working on, but I need to catch for exceptions, and retry the same task multiple times before \"aborting\".

The code I

相关标签:
7条回答
  • 2021-01-31 19:27

    util class:

    public class RetryUtil {
    
        public static <R> CompletableFuture<R> retry(Supplier<CompletableFuture<R>> supplier, int maxRetries) {
            CompletableFuture<R> f = supplier.get();
            for(int i=0; i<maxRetries; i++) {
                f=f.thenApply(CompletableFuture::completedFuture)
                    .exceptionally(t -> {
                        System.out.println("retry for: "+t.getMessage());
                        return supplier.get();
                    })
                    .thenCompose(Function.identity());
            }
            return f;
        }
    }
    

    usage:

    public CompletableFuture<String> lucky(){
        return CompletableFuture.supplyAsync(()->{
            double luckNum = Math.random();
            double luckEnough = 0.6;
            if(luckNum < luckEnough){
                throw new RuntimeException("not luck enough: " + luckNum);
            }
            return "I'm lucky: "+luckNum;
        });
    }
    @Test
    public void testRetry(){
        CompletableFuture<String> retry = RetryUtil.retry(this::lucky, 10);
        System.out.println("async check");
        String join = retry.join();
        System.out.println("lucky? "+join);
    }
    

    output

    async check
    retry for: java.lang.RuntimeException: not luck enough: 0.412296354211683
    retry for: java.lang.RuntimeException: not luck enough: 0.4099777199676573
    lucky? I'm lucky: 0.8059089479049389
    
    0 讨论(0)
提交回复
热议问题