spring webclient: retry with backoff on specific error

前端 未结 4 1438
后悔当初
后悔当初 2021-01-12 16:07

i\'d like to retry the request 3 times after waiting 10sec when response is 5xx. but i don\'t see a method that I can use. On object

WebClient.builder()
             


        
4条回答
  •  旧巷少年郎
    2021-01-12 17:11

    You can do this taking the following approach:

    • Use the exchange() method to obtain the response without an exception, and then throw a specific (custom) exception on a 5xx response (this differs from retrieve() which will always throw WebClientResponseException with either a 4xx or 5xx status);
    • Intercept this specific exception in your retry logic;
    • Use reactor-extra - it contains a nice way to use retryWhen() for more complex & specific retries. You can then specify a random backoff retry that starts after 10 seconds, goes up to an arbitrary time and tries a maximum of 3 times. (Or you can use the other available methods to pick a different strategy of course.)

    For example:

    //...webclient
    .exchange()
    .flatMap(clientResponse -> {
        if (clientResponse.statusCode().is5xxServerError()) {
            return Mono.error(new ServerErrorException());
        } else {
            //Any further processing
        }
    }).retryWhen(
        Retry.anyOf(ServerErrorException.class)
           .randomBackoff(Duration.ofSeconds(10), Duration.ofHours(1))
           .maxRetries(3)
        )
    );
    

提交回复
热议问题