Spring Boot uses an annotation to implement the retry mechanism

Preface

In actual work, reprocessing is a very common scenario, such as:

  • Failed to send message.
  • Failed to call remote service.
  • Failed to compete for lock.

These errors may be caused by network fluctuations. Wait and then reprocess them successfully. try/catchGenerally speaking , whilesyntax such as loops is used for reprocessing, but this approach lacks uniformity, is not very convenient, and requires writing a lot more code.

However spring-retry, through annotations, the reprocessing function can be elegantly implemented without invading the original business logic code.

1. @RetryableWhat is it?

spring-retry of the spring family is another utility module that helps us handle retries of any specific operation in a standard way. In spring-retry, all configurations are based on simple annotations.

I won’t introduce the basics of Spring Boot. I recommend this practical tutorial: https://github.com/javastacks/spring-boot-best-practice

2. Usage steps

1.POM dependency

 <dependency>
  <groupId>org.springframework.retry</groupId>
  <artifactId>spring-retry</artifactId>
 </dependency>

2. Enable @Retryable

@EnableRetry
@SpringBootApplication
public class HelloApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(HelloApplication.class, args);
    }

}

3. Add to the method@Retryable

import com.mail.elegant.service.TestRetryService;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import java.time.LocalTime;

@Service
public class TestRetryServiceImpl implements TestRetryService {
    
    

    @Override
    @Retryable(value = Exception.class,maxAttempts = 3,backoff = @Backoff(delay = 2000,multiplier = 1.5))
    public int test(int code) throws Exception{
    
    
        System.out.println("test被调用,时间:"+LocalTime.now());
          if (code==0){
    
    
              throw new Exception("情况不对头!");
          }
        System.out.println("test被调用,情况对头了!");

        return 200;
    }
}

Let’s briefly explain the meaning of several parameters in the annotation:

  • value: Only when the specified exception is thrown will the include be retried: Like value, the default is empty. When exclude is also empty, all exceptions will be defaulted.
  • exclude:Specify exceptions not to be handled
  • maxAttempts: Maximum number of retries, default 3 times
  • backoff: Retry waiting strategy, used by default @Backoff, @Backoffthe value defaults to 1000L, we set it to 2000L;
  • multiplier(Specify delay multiple) The default is 0, which means a fixed pause of 1 second before retrying. If the multiplier is set to 1.5, the first retry will be 2 seconds, the second retry will be 3 seconds, and the third retry will be 4.5 seconds.

What happens when retries are exhausted and still fails?

When retries are exhausted, RetryOperations can pass control to another callback, the RecoveryCallback. Spring-Retry also provides the @Recover annotation for the @Retryable retry failure post-processing method. If you do not need a callback method, you can simply not write a callback method. The effect is that after the number of retries is over, if it still fails and does not meet the business judgment, an exception will be thrown.

4.@Recover

@Recover
public int recover(Exception e, int code){
    
    
   System.out.println("回调方法执行!!!!");
   //记日志到数据库 或者调用其余的方法
    return 400;
}

You can see that Exception e is written in the passed parameter, which is the connector code used as a callback (if the number of retries is exhausted and it still fails, we throw this Exception e to notify the triggering of the callback method).

Regarding @Recoverannotation methods, special attention should be paid to:

  • ss="nolink">The return value of the method must be @Retryableconsistent with the method
  • The first parameter of the method must be of Throwable type. It is recommended that it @Retryablebe consistent with the configured exception. For other parameters, which parameters are required, just write them in ( @Recoversome of them are included in the method)
  • The callback method and the retry method are written in the same implementation class

5. Precautions

  • Since it is implemented based on AOP , it does not support self-calling methods in classes.
  • If the retry fails and requires @Recoversubsequent processing for the annotated method, then the retry method cannot have a return value and can only be void.
  • It cannot be used within the method try catchand can only throw exceptions outside.
  • @RecoverAnnotation to enable the method called after retry failure (note that it needs to be in the same class as the reprocessing method). The method parameter annotated by this annotation must be a @Retryablethrown exception, otherwise it cannot be recognized. Log processing can be performed in this method. .

Summarize

This article mainly briefly introduces the use of Retryable in Springboot, the main applicable scenarios and precautions. It is still very useful when retrying is needed.

If you like it, please give it a like and support! ! ! ! !
Insert image description here

Guess you like

Origin blog.csdn.net/qq_45442178/article/details/130843717