springboot and retry hello world example
Introduction
This post would demo springboot and retry hello world example, which would use the default retry policy.
Environments
- SpringBoot 1.5.12
- Java 1.8
The SpringBoot version in pom.xml
The dependencies for spring retry with springboot starters in pom.xml
We must add the following dependencies to make the retry example work:
The entry class @SpringBootApplication
You can add @EnableRetry to any @Configuration class.
The mayFailMethod in the service
The code explantion:
- line 0
- we define a variable retryTimes to record the real retry times by spring retry module
- line 1
- this line use the annotation @Retryable to enable the retry policy on method mayFailMethod
- line 2
- In order to know how many times this method is retried, I increment the retryTimes every time the method is called
- line 3
- Sleep for a while to mimic the network latency of a long running method
- line 4
- Because the default retry policy is 3, so ,when retry before 3 times, this method would always fail by throw an Exception
- line 5
- if retry after 3 times, this method would return true.
The test code
If you don’t know how to do unit testing with springboot , you can reference the post: How to do unit testing with springboot hello world example
The code explanation:
- line 0:
- SpringBoot testcase must use the @RunWith(SpringRunner.class) and @SpringBootTest
- line 1:
- We autowired the class under test: RetryService
- line 2:
- We call the mayFailMethod only one time,and make sure that the result is true(assume retry is done successfully)
Run the test code
Let’s run the test code:
As we can see from the console output, the retryService.mayFailMethod() is retried automatically by spring retry, and has retried 3 times. At last, the retry end successfully by return a true value.
It’s so easy, do you think so? You can find the complete code in the github repository bswen github
You can find detail documents about the springboot and unit testing here: