jpadilladev
jpadilladev

Reputation: 1936

Spring Retry and Recovery

is it possible to recover from an exception, and then retry again with Spring Retry?

In Java, would be something like

try{
    doSomething(); // throws Exception
}catch(Exception e){
    recoverException();
    doSomething(); // OK
}

Thanks!!

Upvotes: 2

Views: 7026

Answers (1)

jpadilladev
jpadilladev

Reputation: 1936

Finally,

I created a RetryListener and added it to my RetryTemplate. When some exception is thrown, I recover in the onError method from my RetryListener and then the RetryTemplate will retry automatically.

Something like

@Component
public class CustomRetryListener  extends RetryListenerSupport {

    @Override
    public <T, E extends Throwable> void onError(RetryContext context, 
    RetryCallback<T, E> callback,
        Throwable throwable) {
        //recover from throwable
    }

}

And the retry template bean

@Bean
public RetryTemplate retryTemplate(CustomRetryListener listener) {
    RetryTemplate retryTemplate = new RetryTemplate();
    SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
    retryPolicy.setMaxAttempts(2);
    retryTemplate.setRetryPolicy(retryPolicy);
    retryTemplate.registerListener(listener);
    return retryTemplate;
}

Now you can inject the retryTemplate bean wherever you want and use the execute() method to recover from errors.

Upvotes: 3

Related Questions