当我们使用RetryTemplate时,Spring Retry不起作用吗?

问题描述

我已经通过引用from the following course开发了一种重试机制。下面是我在Spring Batch中开发的代码,在此代码@Recover方法中没有被调用。我在这里做什么错了?

@EnableRetry
@Configuration
public class RetryConfig {
    @Value("${retry.interval.in.seconds}")
    private long retryIntervalInSeconds;

    @Value("${max.attempts}")
    private int attempts;
    
    @Bean
    public RetryTemplate mdsRetryTemplate() {
        SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
        retryPolicy.setMaxAttempts(attempts);

        FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
        backOffPolicy.setBackOffPeriod(1000 * retryIntervalInSeconds);
        
        RetryTemplate template = new RetryTemplate();
        template.setRetryPolicy(retryPolicy);
        template.setBackOffPolicy(backOffPolicy);
        return template;
    }
}

下面是控制器

@RestController
@Slf4j
public class BatchJobController {

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    @Qualifier(value = "sampleAcctJob")
    private Job sampleAcctJob;


    @Autowired
    private RetryTemplate retryTemplate;

    @GetMapping(value = "/invoke-job")
    public String handle() throws Throwable {

        long diff = 0;
        JobExecution je= this.invokeJob();
        Date start = je.getCreateTime();
        Date end = je.getEndTime();

        diff = end.getTime() - start.getTime();

        return "All data has been loaded successfully.";
    }

    private JobExecution invokeJob() throws Throwable {
        // PDF Job
        JobParameters pdfParams = new JobParametersBuilder()
                .addString(".id",String.valueOf(System.currentTimeMillis()))
                .addDate("date",new Date()).toJobParameters();

        return retryTemplate.execute(retryContext  -> {
            JobExecution jobExecution = jobLauncher.run(sampleAcctJob,pdfParams);
            if(!jobExecution.getAllFailureExceptions().isEmpty()) {
                log.error("============== sampleAcctJob Job Failed,retrying.... ================");
                throw jobExecution.getAllFailureExceptions().iterator().next();
            }
            logDetails(jobExecution);
            return jobExecution;
        });
    }

    private void logDetails(JobExecution jobExecution) {
        log.info("JOB_NAME = {},JOB_STATUS = {},START_TIME={},END_TIME = {} ",jobExecution.getJobInstance().getJobName(),jobExecution.getStatus(),jobExecution.getStartTime(),jobExecution.getEndTime());
    }
    
    @Recover
    private void recover() {
        System.out.println("===============");
    }
}

解决方法

您正在以编程方式使用retryTemplate,因此需要提供RecoveryCallback作为第二个参数:

  retryTemplate.execute(new MyRetryCallback(),new MyRecoveryCallback());

如果要使用带注释的声明式方法,则需要使用@Retryable注释可重试的方法,并使用@Recover注释恢复方法。

您可以在主页上找到每种方法的示例:https://github.com/spring-projects/spring-retry#quick-start