I have a number of situations where I need to retry a task n-times if it fails (sometimes with some form of back-off-before-retry logic). Generally, if an exception is thrown, the task should be retried up to the max-retry count.
I can easily write something to do this fairly generically, but not wanting to re-invent the wheel I was wondering if anyone can recommend any frameworks for this. The only thing I have been able to find is: Ant Retry but I don't want to use Ant tasks directly in my application.
Thanks
This strategy specifies the number of times it should retry, the delay between each attempt, and the actions to take after a failed attempt.
Microsoft Entity Framework provides facilities for retrying database operations.
First, you need to enable Spring Retry. You can achieve this by adding the @EnableRetry annotation to your @SpringBootApplication or @Configuration class. You can now use @Retryable to annotate any method to be a candidate or retry and @Recover to specify fallback methods.
Spring Retry provides the ability to automatically re-invoke a failed operation. This is helpful when errors may be transient in nature. For example, a momentary network glitch, network outage, server down, or deadlock. You can configure the. spring-retry.
Check out Failsafe. It's a simple, zero-dependency library for performing retries, and supports synchronous and asynchronous retries, Java 8 integration, event listeners, integration with other async APIs, etc:
RetryPolicy retryPolicy = new RetryPolicy() .handle(ConnectException.class, SocketException.class); .withMaxRetries(3); Connection connection = Failsafe.with(retryPolicy).get(() -> connect());
Doesn't get much easier.
You can use RetriableTasks
as outlined in this post: Retrying Operations in Java. You can quite easily change its waiting algorithm if you like.
Sample code:
//creates a task which will retry 3 times with an interval of 5 seconds RetriableTask r = new RetriableTask(3, 5000, new Callable(){ public Object call() throws Exception{ //put your code here } }); r.call();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With