Over a million developers have joined DZone.

Retry Handling With Spring-Retry

Proper retry handling can reduce a lot of issues when software components fail to communicate with each other for any reason.

· Java Zone

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

Whenever software components communicate with each other, there is a chance for temporary self-correcting faults. Such faults include the temporary unavailability of a service, momentary loss of network connectivity, or timeouts that arise when a service is busy. In such situations a proper retry handling can reduce the problems these faults might cause.

In this post we will see how Spring Retry can be used to add robust retry logic to Spring applications. Spring Retry is probably not that well know because it is not listed on the Spring documentation overview. However, you can find it on the Spring Initializr page.

Setup

To use Spring Retry we need to add the following dependency to our project:

<dependency>
  <groupid>org.springframework.retry</groupid>
  <artifactid>spring-retry</artifactid>
  <version>1.1.2.RELEASE</version>
</dependency>

Spring Retry makes use of AOP, so make sure Spring AOP is available:

<dependency>
  <groupid>org.springframework</groupid>
  <artifactid>spring-aop</artifactid>
  <version>4.2.5.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjweaver</artifactId>
  <version>1.8.8</version>
</dependency>

If you are using Spring Boot, you can use spring-boot-starter-aop instead:

<dependency>
  <groupid>org.springframework.boot</groupid>
  <artifactid>spring-boot-starter-aop</artifactid>
</dependency>

To enable Spring Retry we simply have to add @EnableRetry to our application configuration class:

@EnableRetry
@SpringBootApplication // or @Configuration if you are not using Spring Boot
public class RetryExampleApplication {
 // ...
}

Adding Retry Handling With Annotations

We are now ready to add retry handling to methods. To do so, we simply have to annotate the appropriate methods with @Retryable:

@Service
public class MyService {

 @Retryable
 public void simpleRetry() {
 // perform operation that is likely to fail
 }
}

Methods annotated with @Retryable can be called like any other methods. 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.

The retry behavior can be customized in various ways. For example:

@Service
public class MyService {

 @Retryable(value = {FooException.class, BarException.class}, maxAttempts = 5)
 public void retryWithException() {
 // perform operation that is likely to fail
 }

 @Recover
 public void recover(FooException exception) {
 // recover from FooException
 }
}

Here we tell Spring to apply retry handling only if a Exception of type FooException or BarException is thrown. Other exceptions will not cause a retry. maxAttempts = 5 tells Spring to retry the method up to 5 times if it fails.

With @Recover we define a separate recovery method for FooException. This allows us to run special recovery code when a retryable method fails with FooException.

Adding Retry Handling With RetryTemplate

Besides annotations Spring Retry offers a RetryTemplate that can be used to define retry handling in Java code. Like any other bean, a RetryTemplate can simply be configured in our configuration class:

@EnableRetry
@SpringBootApplication // or @Configuration if you are not using Spring Boot
public class RetryExampleApplication {

 @Bean
 public RetryTemplate retryTemplate() {
 SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
 retryPolicy.setMaxAttempts(5);

 FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
 backOffPolicy.setBackOffPeriod(1500); // 1.5 seconds

 RetryTemplate template = new RetryTemplate();
 template.setRetryPolicy(retryPolicy);
 template.setBackOffPolicy(backOffPolicy);

 return template;
 }

 // ...
}

A RetryPolicy determines when an operation should be retried. SimpleRetryPolicy is a RetryPolicy implementation that retries a fixed number of times.

A BackOffPolicy is a strategy interface to control back off between retry attempts. A FixedBackOffPolicy pauses for a fixed period of time before continuing. Some other default BackOffPolicy implementations are ExponentialBackOffPolicy (increases the back off period for each retry) or NoBackOffPolicy (no delay between retries).

We can now inject the RetryTemplate to our service. To run code with retry handling we simply have to call RetryTemplate.execute():

@Service
public class RetryService {

 @Autowired
 private RetryTemplate retryTemplate;

 public void withTemplate() {
 retryTemplate.execute(context -> {
 // perform operation that is likely to fail
 });
 }

 // ...
}

RetryTemplate.exeucte() takes a RetryCallback<T, E> as parameter. RetryCallback is a functional interface so it can be implemented using a Java 8 Lambda expression (as shown above).

Summary

Spring retry provides an easy way to add retry handling to spring applications. Retry handling can be added using either annotations (@Retryable and @Recover) or by passing a RetryCallback to a RetryTemplate.

You can find the full example source code on GitHub.

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:
java ,spring

Published at DZone with permission of Michael Scharhag, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}