Hands-on Practice Spring Retry retry Framework

Source: Internet
Author: User
Tags try catch

Pre-order

New Year's Day, I wish you all happy, less write bugs

What is Spring retry?

Spring Retry is a functional feature that is independent of spring batch, which mainly implements retry and fuse.

When do you use it?

A remote call timed out and a sudden network outage can be retried. There is a scene limit for retries, and not all scenarios are suitable for retries, such as invalid parameter checking, write operation, etc. (to consider whether the write is idempotent, etc.) are not suitable for retry.

How to use it?

1, first we create a new MAVEN project (if not, please step http://www.cnblogs.com/JJJ1990/p/8384386.html, please ignore), and then introduce the Spring Retry jar package in the Pom file, The code is as follows:

1   <!--spring-retry retry mechanism--  2         <dependency>3             <groupId> Org.springframework.retry</groupid>4             <artifactId>spring-retry</artifactId>5              <version>1.1.2.RELEASE</version>6         </dependency>

2, write the retry part of the code, we directly in the app class's main method to implement

First we set the retry strategy, that is, when the exception occurs, we retry several times, how long each interval, etc.

In the following code, the first behavior creates a new retry template, the second behavior develops a simple retry policy, paying particular attention to the last number 3, which is the number of times we set to retry

1 Final New retrytemplate (); 2         Final New Simpleretrypolicy (33                 extends throwable>,4                 Boolean>singletonmap (Exception.  Classtrue));

3, set the Backoff policy below, note the second row 2000 for each interval of time, unit MS, and then set the retry policy and Backoff policy to the retry template as in line 3.4

1 New Fixedbackoffpolicy (); 2         Fixedbackoffpolicy.setbackoffperiod (+); 3         Retrytemplate.setretrypolicy (policy); 4         Retrytemplate.setbackoffpolicy (Fixedbackoffpolicy);

4, write the retry business part of the code as follows, mainly to implement the Retrycallback interface Dowithretry method, in which is to write the main business logic. I'm simulating an exception in this block, using an array subscript out-of-bounds exception to retry

1 Finalretrycallback<string, exception> retrycallback =NewRetrycallback<string, exception>() {2              PublicString Dowithretry (Retrycontext context)throwsException {3System.out.println (NewDate ());4System.out.println ("Retrycallback");5String [] str =NewString [2];6STR[3] = "";7                 return"1";8             }9};

5, write the recovery callback code as follows, is also the implementation of the Recover method in the Recoverycallback interface, the role of this method is when the 4th step retry code after the retry policy is complete, still exception, it will execute the following code, so you can use the following code, To avoid exceptions.

1 Final New Recoverycallback<string>() {2public             throws  Exception {  3                 System.out.println ("Recoverycallback"); 4                 return NULL ; 5             }6         };

6. Write retry template to execute retry code and recover callback code

1 Try {2             System.out.println ("Retrytemplate execute Start"); 3             String response = Retrytemplate.execute (retrycallback, recoverycallback); 4             System.out.println ("Retrytemplate execute End"); 5         Catch (Exception e) {6            e.printstacktrace (); 7         }

Test code

Start the program, note that the entire code is implemented in the main method, we directly start the program to see the print log information, from the log information can be learned that we start the program after the Execute method, and then execute Retrycallback, But every time there is an array subscript the more abnormal, so he retries 3 times, and each time interval is our set 2 seconds, when the third execution fails, the Recovercallback method is called, and then the entire program ends.

What are the fallback strategies?

1, the fallback policy used in our code above is a fixed interval, and there are several other Backoff strategies as follows:

    • Nobackoffpolicy: No Backoff algorithm policy, retry immediately on each retry

    • Fixedbackoffpolicy: A fixed-time backoff policy that sets parameters sleeper and Backoffperiod,sleeper to specify the wait policy, Default is Thread.Sleep, that is, thread hibernation, backoffperiod specify sleep time, default 1 seconds

    • Uniformrandombackoffpolicy: The stochastic time Backoff strategy, which needs to set sleeper, Minbackoffperiod, and Maxbackoffperiod, which is in the [Minbackoffperiod, Take a random sleep time between maxbackoffperiod, minbackoffperiod default 500 milliseconds, maxbackoffperiod default 1500 ms

    • Exponentialbackoffpolicy: An exponential backoff strategy that sets parameters sleeper, Initialinterval, Maxinterval, and Multiplier,initialinterval to specify the initial sleep time, The default is 100 milliseconds, maxinterval specifies the maximum sleep time, the default is 30 seconds, multiplier specifies the multiplier, that is, the next sleep time is the current sleep time *multiplier

    • Exponentialrandombackoffpolicy: Stochastic exponential backoff strategy, stochastic multiplier can be introduced to realize stochastic multiplier fallback

We will modify the code for the 3rd step as follows:

1 New Exponentialbackoffpolicy (); 2         Exponentialbackoffpolicy.setinitialinterval (+); 3         Exponentialbackoffpolicy.setmultiplier (3); 4         Exponentialbackoffpolicy.setmaxinterval (the); 5         Retrytemplate.setretrypolicy (policy); 6         Retrytemplate.setbackoffpolicy (Exponentialbackoffpolicy);

In the code above, 2000 is the time interval for execution, 3 is a multiple, and 5000 is the maximum allowable interval, and the execution code results are as follows:

For example, the first execution and the second execution interval is 2 seconds, the second and third intervals are 2*3=6 seconds, but the retry is triggered at 5 seconds due to the maximum interval set.

Retry the exception in the business do not capture

In our retry business code we need to retry based on the exception, what happens if you catch an exception in the business code? Let's modify the 4th step code to see:

1 Finalretrycallback<string, exception> retrycallback =NewRetrycallback<string, exception>() {2              PublicString Dowithretry (Retrycontext context)throwsException {3System.out.println (NewDate ());4System.out.println ("Retrycallback");5                 Try {6String [] str =NewString [2];7STR[3] = "";8}Catch(Exception e) {9                     //Todo:handle ExceptionTen                 } One                  A                 return"1"; -             } -};

As above, it is very simple, we directly put an array exception try catch, and then run the code results as follows

As you can see from the information, the code that originally had the exception was executed only once, and the recovery callback code was not called.

So if you need to perform a retry, do not capture the exception information that you need to retry.

So if you need to perform a retry, do not capture the exception information that you need to retry.

So if you need to perform a retry, do not capture the exception information that you need to retry.

Important Words three times ~ ~ ~

  

Build a simple springboot environment by yourself

Hands-on Practice Spring Retry retry Framework

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.