Retry logic with CompletableFuture

后端 未结 7 2297
别跟我提以往
别跟我提以往 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:26

    Instead of implementing your own retry logic, I recommend using a proven library like failsafe, which has built-in support for futures (and seems more popular than guava-retrying). For your example, it would look something like:

    private static RetryPolicy retryPolicy = new RetryPolicy()
        .withMaxRetries(MAX_RETRIES);
    
    public CompletableFuture executeActionAsync() {
        return Failsafe.with(retryPolicy)
            .with(executor)
            .withFallback(null)
            .future(this::executeMycustomActionHere);
    }
    

    Probably you should avoid .withFallback(null) and just have let the returned future's .get() method throw the resulting exception so the caller of your method can handle it specifically, but that's a design decision you'll have to make.

    Other things to think about include whether you should retry immediately or wait some period of time between attempts, any sort of recursive backoff (useful when you're calling a web service that might be down), and whether there are specific exceptions that aren't worth retrying (e.g. if the parameters to the method are invalid).

提交回复
热议问题