Retry a method based on result (instead of exception)

orirab :

I have a method with the following signature:

public Optional<String> doSomething() {
    ...
}

If I get an empty Optional I'd like to retry this method and only after 3 times return the empty Optional.

I've looked and found the Retryable spring annotation, but it seems to only work on Exceptions.

If possible I'd like to use a library for this, and avoid:

  • Creating and throwing an exception.
  • Writing the logic myself.
Cristian Rodriguez :

I have been using failsafe build in retry. You can retry based on predicates and exceptions.

Your code would look like this:

    private Optional<String> doSomethingWithRetry() {
        RetryPolicy<Optional> retryPolicy = new RetryPolicy<Optional>()
                .withMaxAttempts(3)
                .handleResultIf(result -> {
                    System.out.println("predicate");
                    return !result.isPresent();
                });

        return Failsafe
                .with(retryPolicy)
                .onSuccess(response -> System.out.println("ok"))
                .onFailure(response -> System.out.println("no ok"))
                .get(() -> doSomething());
    }

    private Optional<String> doSomething() {
         return Optional.of("result");
    }

If the optional is not empty the output is:

predicate
ok

Otherwise looks like:

predicate
predicate
predicate
no ok

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=70082&siteId=1