Retry policies, in the Filesafe library, express when retries should be performed for an execution. This article will cover several RetryPolicy features like attempts, delays, duration, aborts, etc.
2. Attempts
In retry policy we could configure a maximum number of attempts. By default, three attempts are used for an execution. Retrying without any limitation requires this parameter to be set to -1.
The following code presents how to set maximum attempts for the policy:
we can also set the max number of attempts:
This method has the same effect as setting one less than withMaxAttempts(...). For example, 2 retries equal to 3 attempts.
3. Delays
By default, there are no delays between attempts. To set the delay that will occur between retries use the withDelay(...) method like in the following example:
This configuration will stop the next attempt for 5 seconds.
We can also set random delay for specific range:
Or even set delay that backs off exponentially:
4. Duration
Failsafe library allows us to set max duration for execution, after which retries will stop:
5. Aborts
We can specify which results, failures or conditions to abort retries on:
6. Failure
RetryPolicy can be configured to handle only certain results or failures, in combination with any of the configuration described above:
7. Event Listeners
The RetryPolicy can notify you when an execution attempt fails or before a retry is performed
8. JUnit Test
Let's check the JUnit test that simulates connection problems. In our test, the maximum number of attempts is set to 5. With mockito we make the first 3 attempts fail with ConnectException. Delay is set to 5 seconds.
The output:
9. Conclusion
In this article, we presented several RetryPolicy configurations. Failsafe API is very rich, allows us to set many different parameters like several attempts, delays between them, duration, and aborts.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}