Retry mechanism of SpringBoot learning

Development scenario

When we interface with other third parties, it is normal to succeed or fail once, but occasionally we encounter third-party network exceptions or response exceptions. Or when you call someone else's interface callback. It may take multiple attempts to get the response.

SpringBoot implements retry mechanism

  • Introduce the pom.xml corresponding to the response jar Maven
       <dependency>
         <groupId>org.springframework.retry</groupId>
         <artifactId>spring-retry</artifactId>
        </dependency>
  • Annotate the startup class @EnableRetry
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
@EnableRetry
public class App {
    @Bean
    public RestTemplate restTemplate(){
       return new RestTemplate();
    }
    public static void main(String[] args) {
        System.out.println("hello start");
        SpringApplication.run(App.class, args);
        System.err.println("hello end");
    }
}

  • Annotate the configuration on the Servcie method that needs to be retried
@Service
public class RetryServiceImpl implements RetryService {
	
	public   int count = 0;
	
	public long t = 0;

	@Override
	@Retryable(value = RetryException.class, maxAttempts = 3, backoff = @Backoff(delay = 1000 * 2, multiplier = 1.5))
	public void TestRetryMethod(String name) {
		// TODO Auto-generated method stub
		count++;
		Long s  = System.currentTimeMillis();
		t = s;
		if(name == null) {
			System.err.println("第"+count+"次尝试"+System.currentTimeMillis());
			throw new RetryException("retry");
		}
	}

}

Retryable annotation analysis value

	/**
	 * Exception types that are retryable. Synonym for includes(). Defaults to empty (and
	 * if excludes is also empty all exceptions are retried).
	 * @return exception types to retry
	 */
	Class<? extends Throwable>[] value() default {};

Through the English comments, you can know that the retry mechanism will only be used when the exception is thrown.

Retryable annotation analysis maxAttempts

	/**
	 * @return the maximum number of attempts (including the first failure), defaults to 3
	 */
	int maxAttempts() default 3;

The maximum number of attempts is not configured and the default is 3 times.

backoff annotation analysis delay

	/**
	 * A canonical backoff period. Used as an initial value in the exponential case, and
	 * as a minimum value in the uniform case.
	 * @return the initial or canonical backoff period in milliseconds (default 1000)
	 */
	long delay() default 0;

Try again after how many milliseconds.

backoff annotation analysis multiplier

This is a multiple of the time interval. For example, if you configure a delay of 1000 and a multiplier of 2, it means that the first attempt is 1 second, the second is 2 seconds, the third is 4 seconds, and so on.

Summary: The underlying principle is the idea of ​​aop.

test

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_29897369/article/details/91347075