Sunday, February 17, 2013

Retrying Operations using Spring's RetryTemplate

Back in 2009, I blogged about Retrying Operations in Java in which I covered three different approaches to retrying operations on failure. Here is another alternative:

If your application is using Spring then it is easier to use the Spring Framework's RetryTemplate.

The example below shows how you can use a RetryTemplate to lookup a remote object. If the remote call fails, it will be retried five times with exponential backoff.

// import the necessary classes
import org.springframework.batch.retry.RetryCallback;
import org.springframework.batch.retry.RetryContext;
import org.springframework.batch.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.batch.retry.policy.SimpleRetryPolicy;

// create the retry template
final RetryTemplate template = new RetryTemplate();
template.setRetryPolicy(new SimpleRetryPolicy(5));
final ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();

// execute the operation using the retry template
template.execute(new RetryCallback<Remote>() {
  public Remote doWithRetry(final RetryContext context) throws Exception {
    return (Remote) Naming.lookup("rmi://somehost:2106/MyApp");
Related Posts:
Retrying Operations in Java

1 comment:

  1. Can you please explain how this is configured? Is retryTemplate take the place of the processor? The spring documentation doesn't explain this either. And, to vent about spring-batch, I find it nonsensical that you need to write a template class just to specify a delay between retries. What is the point of retries if there is no delay? Why make it easy to specify your retry exception but so hard to specify a delay? I am waiting for a upgrade to jrugged and will gladly use that instead since specifying a delay in spring-batch is so convoluted.


Note: Only a member of this blog may post a comment.