首页 > 解决方案 > 如何根据异常更改spring重试模板固定退避策略

问题描述

我正在使用 Spring 重试模板进行重试。

这是我的重试方法,这里我的重试间隔应该基于异常。例如,如果抛出 DataException,则应在 1000(1 秒)的时间间隔内重试,或者如果抛出 MQException,则应在 5000(5 秒)的时间间隔内重试。

如何根据异常更改 FixedBackOffPolicy 实例。

主要流程:

private void retryTest(){
                retryTemplate.execute(context -> {
                    log.info("Processing request...");
                    retryTest1();
                    return true; 
                },
                context -> {
                    log.info("Recovering request...");
                    return true;
                });

    }  

private void retryTest1(){
    throw new DataException("Data exception"); 
     //throw new MQException("MQ Message exception"); 
}

重试模板初始化:

@Bean
    public RetryTemplate retryTemplate() {
        RetryTemplate retryTemplate = new RetryTemplate();

        FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
        fixedBackOffPolicy.setBackOffPeriod(1000L);
        retryTemplate.setBackOffPolicy(new CustomBackOffPolicy());  // Custom backoff policy 

        SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
        retryPolicy.setMaxAttempts(5);
        retryTemplate.setRetryPolicy(retryPolicy);

        
        return retryTemplate;
    }


public class CustomBackOffPolicy implements BackOffPolicy {

    @Autowired
    RetryTemplate retryTemplate;


    @Override
    public BackOffContext start(RetryContext retryContext) {
          RetryPolicy retryPolicy = (RetryPolicy) retryContext;

          return null;
    }

    @Override
    public void backOff(BackOffContext backOffContext) throws BackOffInterruptedException {
        try {
            Thread.sleep(1000l);
        } catch (InterruptedException var2) {
            throw new BackOffInterruptedException("Thread interrupted while sleeping", var2);
        }
    }

标签: springspring-bootspring-retry

解决方案


你需要一个自定义的BackOffPolicyRetryContext您可以从方法中获取异常类型start()

ExceptionClassifierRetryPolicy您可以使用与基于异常类型委托不同重试策略中使用的技术类似的技术。


推荐阅读