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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM