DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Frameworks
  4. Retry Handling With Spring-Retry

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.

Michael Scharhag user avatar by
Michael Scharhag
·
Apr. 04, 16 · Opinion
Like (9)
Save
Tweet
Share
36.91K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Spring Framework

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How to Submit a Post to DZone
  • Top Three Docker Alternatives To Consider
  • How To Create and Edit Excel XLSX Documents in Java
  • Top 5 Java REST API Frameworks

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: