Spring Retry retry mechanism

When calling a third-party interface or using mq, there will be network anomalies such as network jitter, connection timeout, etc., so you need to retry. To make processing more robust and less prone to failure, subsequent attempted operations sometimes help the failed operation to succeed. For example, a remote call to a web service or RMI service due to a network failure or a DeadLockLoserException in a database update may resolve itself after a short wait. To automate retries for these operations, Spring Batch has the RetryOperations strategy. However, the retry function is independent from the Spring Batch 2.2.0 version and becomes the Spring Retry module.

import dependencies

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

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
    </dependency>

Need to introduce the dependencies of Spring-retry and aspectjweaver.

entry class


@SpringBootApplication
@EnableRetry
public class SpringbootRetryApplication {

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

Enable retry interception on the entry class and use @EnableRetryannotations.

Service

@Service
public class PayService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private final int totalNum = 100000;

    @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 2000L, multiplier = 1.5))
    public int minGoodsnum(int num) throws Exception {
        logger.info("减库存开始" + LocalTime.now());
        try {
            int i = 1 / 0;
        } catch (Exception e) {
            logger.error("illegal");
        }
        if (num <= 0) {
            throw new IllegalArgumentException("数量不对");
        }
        logger.info("减库存执行结束" + LocalTime.now());
        return totalNum - num;
    }
}

@RetryableParameter description:

  • value: The specified exception will be thrown before retrying
  • include: same as value, the default is empty, when exclude is also empty, the default is abnormal
  • exclude: specify exceptions not to be handled
  • maxAttempts: the maximum number of retries, the default is 3 times
  • backoff: retry waiting strategy, used by default @Backoff, @Backoffthe default value is 1000L, we set it to 2000L; the default value of multiplier (specified delay multiple) is 0, which means that the retry will be performed after a fixed pause of 1 second. If the multiplier is set to 1.5, the first One retry is 2 seconds, the second is 3 seconds, and the third is 4.5 seconds.

test class

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootRetryApplicationTests {
    @Autowired
    private PayService payService;

    @Test
    public void payTest() throws Exception {
        int store = payService.minGoodsnum(-1);
        System.out.println("库存为:" + store);
    }

}

The console result of running is as follows:

As you can see, an IllegalArgumentExceptionexception is thrown after three times.

When retries are exhausted, RetryOperations can pass control to another callback, RecoveryCallback. Spring-Retry also provides the @Recover annotation, which is used for the @Retryable retry failure post-processing method. The exception in this method must be the exception thrown in the @Retryable method, otherwise this method will not be called.

@Recover
public int recover(Exception e) {
    logger.warn("减库存失败!!!" + LocalTime.now());
    return totalNum;
}

In the Service, after adding the above method, test it.

It can be seen that when the three retries are completed, the Recovery method will be called, and the exception will not be thrown again.

Summarize

This article mainly talks about the simple application of Spring-Retry in the Spring Boot project. It mainly configures some retry strategies based on annotations, which is relatively simple to use. The main applicable scenarios are when calling third-party interfaces or using mq. Due to network anomalies such as network jitter, connection timeout, etc., you need to retry at this time.

Code for this article: https://github.com/keets2012/Spring-Cloud_Samples/tree/master/springboot-retry

Subscribe to the latest articles, welcome to pay attention to my public number

WeChat public account

refer to

  1. Springboot integrates retry (retry mechanism)

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326690863&siteId=291194637