Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Spring Retry template to retry max attempts: infinite

I would like to modify DB connection creation with Spring Retry to try again if DB is down at application startup. I would not like to limit the number of retries. How should I configure the policy to do that.

My current code (I know in this state it limits to 100):

SimpleRetryPolicy policy = new SimpleRetryPolicy(100, Collections.singletonMap(Exception.class, true));

// Use the policy...
RetryTemplate template = new RetryTemplate();
template.setRetryPolicy(policy);
Connection conn = template.execute(new RetryCallback<Connection, Exception>() {
    public Connection doWithRetry(RetryContext context) throws Exception {
        return getConnectionFactory().createConnection();
    }
});

How should I modify this code?

like image 467
user2695543 Avatar asked Feb 15 '18 20:02

user2695543


People also ask

How do I enable retry in spring boot?

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.

What is retry template in spring?

Spring Retry provides an ability to automatically re-invoke a failed operation. This is helpful where the errors may be transient (like a momentary network glitch).

Does spring retry block thread?

However, whenever the execution of a retryable method fails with an exception, Spring will automatically retry to call the method up to three times. By default Spring uses a 1 second delay between method calls. Please note that the calling thread blocks during retry handling.

What is RetryContext?

public interface RetryContext extends org.springframework.core.AttributeAccessor. Low-level access to ongoing retry operation. Normally not needed by clients, but can be used to alter the course of the retry, e.g. force an early termination.


1 Answers

Use AlwaysRetryPolicy instead of SimpleRetryPolicy.

But you might want to add a BackOffPolicy to wait between retries.

You can then interrupt the thread to shut everything down.

like image 53
Gary Russell Avatar answered Sep 24 '22 15:09

Gary Russell