Software Development

Using Spring Retry API

Did a method just throw an Exception? Well, we could re-invoke it a few times more before giving up using Spring’s Retry API. Last time we touched on BackOff and related interfaces and classes which is used in this API.

Requirements

Stuff used in this post.

  • Spring Boot 1.5.4.RELEASE
  • spring-retry
    • we require this Maven dependency in our pom.xml
  • Java 8

@Retryable

Although there is this declarative option, we’ll not cover that here. It’s usage may be more related to Spring Batch as we are unable to override that annotation’s attributes. For instance, setting maxAttempts  like in the codes below don’t work and @Retryable  defaults to maxAttemptes = 3 .

[wp_ad_camp_5]

Using the Retry API

There are essentially 4 things to consider when using this API:

  1. A method invocation that may fail.
  2. A method invocation to recover from a failure after n  retries.
  3. Methods’ return values
  4. Using RetryTemplate  class

Our Sample Codes

This is our service class. It has several methods for test with the API.

  1. Methods with return value
    • getAllCodes_ThrowException
      • Always throws an Exception
    • getAllCodes_Recovery
      • Recovery method
    • getAllCodes_Ok
      • Does not throw Exceptions
      • Always works and returns a list of String objects
  2. Methods with void return type
    • updateCode_ThrowException
      • Always throws an Exception
    • updateCode_Recovery
      • Recovery method
    • updateCode_Ok
      • Does not throw Exceptions

[wp_ad_camp_4]

Next is our @Configuration  class. Notice I commented out stuff related to FixedBackOffPolicy and used ExponentialBackOffPolicy. Either one can be used interchangeably depending on our requirements.

[wp_ad_camp_3]

Lastly, our main class. We’ll place the actual codes to test between /** Start **/  and /** End **/

Testing

With Return Value, Exception and Recovery method

[wp_ad_camp_2]

With Return Value, Recovery Method, No Exception

Outputs:

Void Return Type, Exception, and Recovery Method

Outputs:

Void Return Type, Recovery Method, No Exception

Outputs:

[wp_ad_camp_1]

Download the Codes

https://github.com/Turreta/Using-Spring-Retry-API

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like