Practice spring retry framework by yourself, springretry
Preface
Chinese New Year is coming soon. I wish you a happy New Year and less bug writing.
What is spring retry?
Spring retry is an independent function of spring batch, which implements retry and circuit breaking.
When will it be used?
If the remote call times out and the network is suddenly interrupted, you can try again. There are restrictions on retry scenarios, not all of which are suitable for retry. For example, parameter verification is invalid, write operations, and so on (whether the write is a power or not) are not suitable for retry.
How to use it?
1. First, create a maven Project (if not, go to http://www.cnblogs.com/jjj1990/p/8384386.html, ), and then introduce the jar package of spring retry in the pom file. The Code is as follows:
1 <! -- Spring-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, which is directly implemented in the main method of the app class.
First, we have formulated a retry policy, that is, when an exception occurs, we retry several times and how long each interval is.
In the following code, the first action creates a retry template, and the second action creates a simple retry policy. Pay special attention to the last number 3, which is the number of retries we set.
1 final RetryTemplate retryTemplate = new RetryTemplate();2 final SimpleRetryPolicy policy = new SimpleRetryPolicy(3, 3 Collections.<Class<? extends Throwable>,4 Boolean>singletonMap(Exception.class, true));
3. Next, set the backoff policy. Note that the second line 2000 is the interval, in ms. Then, set the retry policy and backoff policy to the row 3.4 In the retry template.
1 FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();2 fixedBackOffPolicy.setBackOffPeriod(2000);3 retryTemplate.setRetryPolicy(policy);4 retryTemplate.setBackOffPolicy(fixedBackOffPolicy);
4. Write the retry Service Code as follows, mainly the doWithRetry method for implementing the RetryCallback interface, in which the main business logic is compiled. I simulated an exception in this section and tried again through an array subscript out-of-bounds exception.
1 final RetryCallback<String, Exception> retryCallback = new RetryCallback<String, Exception>() {2 public String doWithRetry(RetryContext context) throws Exception {3 System.out.println(new Date());4 System.out.println("retryCallback");5 String [] str = new String [2];6 str[3] = "";7 return "1";8 }9 };
5. Write the recovery callback Code as follows, which also implements the recover method in the RecoveryCallback interface. The function of this method is that after the retry code in step 1 is executed according to the retry policy, the system still encounters an exception, then the following code will be executed, so that you can avoid exceptions through the following code.
1 final RecoveryCallback<String> recoveryCallback = new RecoveryCallback<String>() {2 public String recover(RetryContext context) throws Exception {3 System.out.println("recoveryCallback");4 return null;5 }6 };
6. Write a retry template to execute the retry code and restore the 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 can directly start the program to view the printed log information, which can be learned from the log information, after starting the program, we first enter the execute method and then execute retrycallback. However, every execution has an exception in the array, so he retries three times, in addition, the interval is set to 2 seconds. When the third execution fails, the recovercallback method is called and the whole program ends.
What are the return policies?
1. The return policy used in the above Code is a fixed interval, and there are several other backoff policies as follows:
-
NoBackOffPolicy: No Backoff Algorithm policy. Retry immediately upon each retry.
-
FixedBackOffPolicy: a fixed-time backoff policy. You need to set the sleeper and backOffPeriod parameters. sleeper specifies the waiting policy. The default value is Thread. sleep, that is, Thread sleep, And backOffPeriod. The default value is 1 second.
-
Random: Random Time backoff policy. sleeper, minBackOffPeriod, and maxBackOffPeriod must be set. This policy takes a random sleep time between [minBackOffPeriod and maxBackOffPeriod. The default value of minBackOffPeriod is 500 milliseconds.
-
ExponentialBackOffPolicy: Exponential Backoff policy. The sleeper, initialInterval, maxInterval, and multiplier parameters must be set. initialInterval specifies the initial sleep time. The default value is 100 milliseconds, and maxInterval specifies the maximum sleep time, multiplier specifies the multiplier, that is, the next sleep time is the current sleep time * multiplier
-
ExponentialRandomBackOffPolicy: Random Index backoff policy. The random multiplier can be used to return the random multiplier.
We will modify the code in step 1 as follows:
1 ExponentialBackOffPolicy exponentialBackOffPolicy = new ExponentialBackOffPolicy();2 exponentialBackOffPolicy.setInitialInterval(2000);3 exponentialBackOffPolicy.setMultiplier(3);4 exponentialBackOffPolicy.setMaxInterval(5000);5 retryTemplate.setRetryPolicy(policy);6 retryTemplate.setBackOffPolicy(exponentialBackOffPolicy);
In the above Code, 2000 is the execution interval, 3 is a multiple, and 5000 is the maximum allowed interval. The execution result is as follows:
For example, the interval between the first and second executions is 2 seconds. The interval between the second and third executions is originally 2*3 = 6 seconds, however, because the maximum interval is set, a Retry is triggered in 5 seconds.
Do not capture exceptions during business retries
In our retry business code, we need to retry based on exceptions. What if you capture exceptions in the Business Code ?? Let's modify the code in step 3:
1 final RetryCallback<String, Exception> retryCallback = new RetryCallback<String, Exception>() { 2 public String doWithRetry(RetryContext context) throws Exception { 3 System.out.println(new Date()); 4 System.out.println("retryCallback"); 5 try { 6 String [] str = new String [2]; 7 str[3] = ""; 8 } catch (Exception e) { 9 // TODO: handle exception10 }11 12 return "1";13 }14 };
As shown above, it is very simple to directly try catch the array exception, and then run the code and the result is as follows:
For example, it can be seen from the information that the Exception Code was executed only once and the callback code was not called.
Therefore, if you need to retry, do not capture the exception information you need to retry.
Therefore, if you need to retry, do not capture the exception information you need to retry.
Therefore, if you need to retry, do not capture the exception information you need to retry.
Important: three times ~~~
Build a simple SpringBoot environment by yourself