Spring / Spring Retry Interview Questions
How do you implement a custom RetryPolicy in Spring Retry?
You can implement a custom RetryPolicy by implementing the RetryPolicy interface, which gives you full control over whether a retry should be allowed based on any criteria β not just exception type or count. Custom policies are useful when retry decisions depend on application-specific state, such as response content, quota availability, or external configuration.
RetryPolicy interface contract:
public interface RetryPolicy { boolean canRetry(RetryContext context); RetryContext open(RetryContext parent); void close(RetryContext context); void registerThrowable(RetryContext context, Throwable throwable); }
Custom policy example β retry on specific error codes in the exception message:
public class ErrorCodeRetryPolicy implements RetryPolicy { private final int maxAttempts; public ErrorCodeRetryPolicy(int maxAttempts) { this.maxAttempts = maxAttempts; } @Override public boolean canRetry(RetryContext context) { Throwable last = context.getLastThrowable(); if (last == null) return true; // first attempt boolean isRetryableCode = last.getMessage() != null && last.getMessage().contains("RETRY_CODE"); return isRetryableCode && context.getRetryCount() < maxAttempts; } @Override public RetryContext open(RetryContext parent) { return new SimpleRetryContext(parent); } @Override public void close(RetryContext context) {} @Override public void registerThrowable(RetryContext context, Throwable throwable) { ((SimpleRetryContext) context).registerThrowable(throwable); } }
Register it on a RetryTemplate with template.setRetryPolicy(new ErrorCodeRetryPolicy(4)).
More Related questions...