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?
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 an ability to automatically re-invoke a failed operation. This is helpful where the errors may be transient (like a momentary network glitch).
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.
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.
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.
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