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
Partner Zones AWS Cloud
by AWS Developer Relations
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
Partner Zones
AWS Cloud
by AWS Developer Relations

Trending

  • How To Check IP Addresses for Known Threats and Tor Exit Node Servers in Java
  • Logging Best Practices Revisited [Video]
  • What Is Test Pyramid: Getting Started With Test Automation Pyramid
  • Explainable AI: Making the Black Box Transparent
  1. DZone
  2. Coding
  3. Frameworks
  4. How to Use Spring Retry Template

How to Use Spring Retry Template

I am going to talk about one of the solutions in Java with spring-context on how to use the Spring Retry Template to handle the failure operations.

Anil Manjappa user avatar by
Anil Manjappa
CORE ·
Jun. 30, 20 · Tutorial
Like (8)
Save
Tweet
Share
32.76K Views

Join the DZone community and get the full member experience.

Join For Free

In the cloud computing world, one of the pivotal parts is networking, the fact is that we cannot avoid network glitches and there will be temporary disconnection for a couple of seconds which makes the operations break while doing network-related configuration from the cloud-native applications. I am going to talk about one of the solutions in Java with spring-context on how to use the Spring Retry Template to handle the failure operations. We will build a small application and see how Spring Retry Template works.

Pre-Requisites

  • Spring Boot 2.3.x
  • Maven
  • IDE STS/Eclipse

Maven Dependency

Plain Text
 




xxxxxxxxxx
1


 
1
<dependency>
2
    <groupId>org.springframework.retry</groupId>
3
    <artifactId>spring-retry</artifactId>
4
</dependency>



Create Spring Retry Template Bean

Java
 




xxxxxxxxxx
1
19


 
1
@Configuration
2
@EnableRetry
3
public class BeanSeederServices {
4

          
5
    @Bean
6
    public RetryTemplate retryTemplate() {
7
        SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
8
        retryPolicy.setMaxAttempts(4);
9

          
10
        FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
11
        backOffPolicy.setBackOffPeriod(3000);
12

          
13
        RetryTemplate template = new RetryTemplate();
14
        template.setRetryPolicy(retryPolicy);
15
        template.setBackOffPolicy(backOffPolicy);
16

          
17
        return template;
18
    }
19
}



Create a bean configuration class to manage required beans, use @EnableRetry annotation to enable spring retry and create a RetryTemplate bean, so that this bean can be used throughout the spring boot application to retry the failed operations. We have configured maximum re-try attempts to 4 with SimpleRetryPolicy and having back to back retries can cause locking of the resources, so we should add a BackOff policy to create a gap between retries. 

By default, each operation is retried for a maximum of three attempts with no back off in between.

Put Retry-able Logic in the Service 

Java
 




x



1
@Service
2
public class ConfigureNetworkService
3
{
4
 @Autowired
5
 private RetryTemplate retryTemplate;
6
  
7
 int counter =0;
8
  
9
  private void configureNetworkSystem(){
10
   retryTemplate.execute(
11
       context -> {
12
                    verifyNwConfiguration();
13
                    return true;
14
  });  
15
  }
16
  
17
  private void verifyNwConfiguration(){
18
    counter++;
19
    LOGGER.info("N/W configuration Service Failed "+ counter);
20
    throw new RuntimeException();
21
  }
22

          
23
}



Execute block keeps executing the callback until it either succeeds or the policy dictates that we stop, in which case the most recent exception thrown by the callback will be rethrown.

Create a REST Endpoint to Test

This client is created just to hit the ConfigureNetworkService configureNetworkSystem() method. 

Java
 




x


 
1
@RestController
2
@RequestMapping(value="/networksrv")
3
public class NetworkClientService {
4
    @Autowired
5
    private ConfigureNetworkService configureNetworkService;
6
    @GetMapping
7
    public String callRetryService() throws SQLException {
8
        return configureNetworkService.configureNetworkSystem();
9
    }
10
}



Launch the URL and See the Logs

http://localhost:8080/networksrv

Plain Text
 




x


 
1
2020-06-16 09:59:51.399  INFO 17288 --- [nio-8080-exec-1] c.e.springretrydemo.NetworkClientService       : N/W configuration Service Failed  1
2
2020-06-16 09:59:52.401  INFO 17288 --- [nio-8080-exec-1] c.e.springretrydemo.NetworkClientService       : N/W configuration Service Failed  2
3
2020-06-16 09:59:53.401  INFO 17288 --- [nio-8080-exec-1] c.e.springretrydemo.NetworkClientService       : N/W configuration Service Failed  3
4
2020-06-16 09:59:53.402  INFO 17288 --- [nio-8080-exec-1] c.e.springretrydemo.NetworkClientService       : N/W configuration Service Failed  4
5
Exception in thread "NetworkClientService" java.lang.RuntimeException



The logs show it has tried the simpleRetry method 4 times and then throw the Runtime exception.

That's the learning from this blog. Let me know other frameworks or other technical feasibility to retry the failed operations.

Spring Framework Template Spring Boot

Opinions expressed by DZone contributors are their own.

Trending

  • How To Check IP Addresses for Known Threats and Tor Exit Node Servers in Java
  • Logging Best Practices Revisited [Video]
  • What Is Test Pyramid: Getting Started With Test Automation Pyramid
  • Explainable AI: Making the Black Box Transparent

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

Let's be friends: