spring-retry 重试机制的使用

时间:2019-10-17
本文章向大家介绍spring-retry 重试机制的使用,主要包括spring-retry 重试机制的使用使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

场景:由于网络抖动原因,或者其他原因,需要对代码重新执行,这个就需要重试了。

import org.springframework.context.annotation.Configuration;
import org.springframework.retry.annotation.EnableRetry;

/**
 * @desc 重试机制配置
 */
@Configuration
@EnableRetry
public class RetryConfig {

}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

import java.time.LocalTime;

@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;
    }

    @Recover
    public int recover(Exception e) {
        logger.warn("减库存失败!!!" + LocalTime.now());
        //记日志到数据库
        return totalNum;
    }
}
    @Autowired
    private PayService payService;

    @GetMapping("/retry")
    public String getNum() throws Exception {
        int i = payService.minGoodsnum(-1);
        System.out.println("===="+i);
        return "succeess";
    }

其他使用方法:https://blog.csdn.net/easy_to_know/article/details/86611839

原文地址:https://www.cnblogs.com/huzi007/p/11692043.html