The p7 boss of Ali shared the unknown skills of spring retry for the first time

Time:2021-8-17

Today’s sharing begins. Please give us more advice~

External services are generally unreliable to callers, especially in the case of poor network environment, network jitter can easily lead to exceptions such as request timeout. At this time, it is necessary to use the failure retry strategy to call the API interface again to obtain. Retry policy is also widely used in service governance to check whether the service survives through regular detection.

Spring exception retry framework

Spring retry supports integration into spring or spring boot projects, and it supports aspect injection writing of AOP. Therefore, the aspectjweaver.jar package must be introduced when importing.

1. Introduce Maven dependency

The p7 boss of Ali shared the unknown skills of spring retry for the first time

2. Add @ retryable and @ recover annotations

@Retryable annotation. When an exception occurs in the annotated method, it will be retried

  • Value: specify the exception to retry
  • Include: like value, it is empty by default. When exclude is also empty, all exceptions will be retried
  • Exclude: Specifies that the exception will not be retried. It is empty by default. When include is also empty, all exceptions will be retried
  • Maxattempts: number of retries. The default is 3
  • Backoff: retry compensation mechanism, not available by default

@Backoff annotation

  • Delay: retry after specifying a delay
  • Multiplier: Specifies the multiple of the delay. For example, when delay = 5000L and multiplier = 2, the first retry is 5 seconds, the second is 10 seconds, and the third is 20 seconds

@Recover comment:When the retry reaches the specified number of times, the annotated method will be called back, and log processing can be carried out in this method. It should be noted that the callback will only occur when the exception is consistent with the input parameter type.

The p7 boss of Ali shared the unknown skills of spring retry for the first time

3. Enable retry function

Add the @ enableretry annotation on the startup class to enable the retry function, or add it on the service using retry, or on the configuration class. It is recommended that all enable configurations be added to the startup class to clearly and uniformly manage the functions used.

The p7 boss of Ali shared the unknown skills of spring retry for the first time

4. Start the service and run the test

The p7 boss of Ali shared the unknown skills of spring retry for the first time

Guava retry component based on guava

See the component author’s introduction to this component directly:

This is a small extension to Google’s guava library to allow for the creation of configurable retrying strategies for an arbitrary function call, such as something that talks to a remote service with flat uptime, For example, the policy of talking to a remote service with unstable running time.)

The first step is to introduce Maven coordinates:

The p7 boss of Ali shared the unknown skills of spring retry for the first time

1. Introduction to main interfaces and Strategies

  • Attempt: perform a task at one time;
  • Attempttimelimiter: single task execution time limit (if the execution of a single task times out, the execution of the current task will be terminated);
  • Blockstrategies: task blocking strategies (generally speaking, what to do during the period when the current task is completed and the next task has not started… — blockstrategies.thread_ SLEEP_ Strategy is to call thread. Sleep (sleeptime);
  • Retryexception: retry exception;
  • Retrylistener: a user-defined retry listener, which can be used to record error logs asynchronously;
  • Stopstrategy: stop retry policy, which provides three types:
  • Stopafterdelaystrategy: set a maximum allowable execution time; For example, set the maximum execution time of 10s. No matter how many times the task is executed, as long as the retry exceeds the maximum time, the task will terminate and return the retry exception retryexception;
  • Neverstopstrategy: do not stop. It is used when it is necessary to rotate training until the desired result is returned;
  • Stopafterattemptstrategy: set the maximum number of retries. If the maximum number of retries is exceeded, the retry will be stopped and a retry exception will be returned;
  • Waitstrategy: wait duration policy (control time interval). The returned result is the next execution duration:
  • Fixedwaitstrategy: fixed waiting time strategy;
  • Randomwaitstrategy: random waiting duration strategy (it can provide a minimum and maximum duration, and the waiting duration is the random value of its interval)
  • Incrementingwaitstrategy: incremental waiting time strategy (provide an initial value and step size, and the waiting time increases with the number of retries)
  • Exponential waitstrategy: exponential waiting time strategy;
  • Fibonacci waitstrategy: Fibonacci waiting time strategy;
  • Exceptionwaitstrategy: exception duration waiting strategy;
  • Composite wait strategy: composite wait strategy;

2. Judge whether to retry according to the result

Usage scenario: if the return value determines whether to retry. Retry interface:

The p7 boss of Ali shared the unknown skills of spring retry for the first time

Test:

The p7 boss of Ali shared the unknown skills of spring retry for the first time

Output:

The p7 boss of Ali shared the unknown skills of spring retry for the first time

3. Judge whether to retry according to the exception

Usage scenario: judge whether to retry according to the type of exception thrown. Retry interface:

The p7 boss of Ali shared the unknown skills of spring retry for the first time

Test:

The p7 boss of Ali shared the unknown skills of spring retry for the first time

Output:

The p7 boss of Ali shared the unknown skills of spring retry for the first time

4. Retry policy – set unlimited retry

Usage scenario: in case of exceptions, retry indefinitely (default execution strategy) until normal and valid results are returned;

The p7 boss of Ali shared the unknown skills of spring retry for the first time

5. Retry strategy – set the maximum number of retries

Usage scenario: in case of exceptions, the maximum number of retries is. If the number exceeds, an exception will be thrown;

The p7 boss of Ali shared the unknown skills of spring retry for the first time

Test:

The p7 boss of Ali shared the unknown skills of spring retry for the first time

Output:

The p7 boss of Ali shared the unknown skills of spring retry for the first time

6. Wait policy – set a fixed waiting time policy for retry

Usage scenario: set the waiting interval for each retry to be fixed at 10s;

The p7 boss of Ali shared the unknown skills of spring retry for the first time

The test output shows that the call interval is 10s:

The p7 boss of Ali shared the unknown skills of spring retry for the first time

7. Waiting strategy – set a fixed growth strategy for retry waiting time

Scenario: set the initial waiting time value and set the fixed growth step, but do not set the maximum waiting time;

The p7 boss of Ali shared the unknown skills of spring retry for the first time

The test output shows that the call interval increases by 1 second:

The p7 boss of Ali shared the unknown skills of spring retry for the first time

8. Waiting strategy – set the retry waiting time to increase exponentially

Usage scenario: increase the waiting time exponentially according to the multiplier value, and set the maximum waiting time;

The p7 boss of Ali shared the unknown skills of spring retry for the first time

The retry strategy and input parameters are not well understood. OK, check the source code:

The p7 boss of Ali shared the unknown skills of spring retry for the first time

It can be seen from the source code that exponentialwaitstrategy is an immutable internal class. Check the input parameters in the constructor. The most important delay time calculation method computesleeptime(), you can see the delay time calculation method

Calculate the value with 2 as the base and the number of failures as the index

The value constructor of the first step is multiplied by the first input parameter and then rounded to obtain the delay time (MS)

According to the above analysis, the input parameter is 1000, and the time interval should be 2, 4 and 8s

The test output shows that the call interval is 2 × 1000,4 × 1000,8 × 1000:

The p7 boss of Ali shared the unknown skills of spring retry for the first time

9. Waiting strategy – set the waiting time for retry according to the Fibonacci sequence strategy

Usage scenario: increase the waiting time according to the Fibonacci sequence according to the multiplier value, and set the maximum waiting time. Fibonacci sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34

The p7 boss of Ali shared the unknown skills of spring retry for the first time

Similarly, from the source code, the calculation shows that the delay time is the product of the Fibonacci sequence and the first input parameter (milliseconds)

The p7 boss of Ali shared the unknown skills of spring retry for the first time

The test output shows that the interval call is 1 × 1000,1 × 1000,2 × 1000:

The p7 boss of Ali shared the unknown skills of spring retry for the first time

10. Waiting strategy – combined retry waiting time strategy

Usage scenario: when the existing policies do not meet the usage scenario, multiple policies can be combined.

The p7 boss of Ali shared the unknown skills of spring retry for the first time

Similarly, you can understand the meaning of combination strategy only by looking at the source code:

The p7 boss of Ali shared the unknown skills of spring retry for the first time

It can be seen that the combined strategy actually adds the delay time of multiple strategies to obtain the delay time of the combined strategy. The delay time of exponential wait is 2, 4, 8, 16, 32… And the delay time of fixed wait is 2, 2, 2, 2, 2… So the total delay time is 4, 6, 10, 18, 34

Test output:

The p7 boss of Ali shared the unknown skills of spring retry for the first time

11. Listener – retrylistener implements the detailed processing of retry process

Usage scenario: customize the listener to print the details of the retry process respectively. In the future, it can be more used for asynchronous logging or special processing.

The p7 boss of Ali shared the unknown skills of spring retry for the first time

Test:

The p7 boss of Ali shared the unknown skills of spring retry for the first time

Output:

The p7 boss of Ali shared the unknown skills of spring retry for the first time

summary

Both methods are elegant retry strategies. Spring retry has simpler configuration and relatively simple functions. Guava itself is a boutique Java class library launched by Google. Guava retry is also very powerful. Compared with spring retry, it has more selectivity in judging whether to retry, which can be used as a supplement to spring retry.