“Spring Retry在使用RetryTemplate时无法正常工作吗?”

huangapple go评论69阅读模式
英文:

Spring Retry doesn't works when we use RetryTemplate?

问题

我已经开发了一个重试机制,参考了以下课程。下面是我在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 {
        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("===============");
    }
}
英文:

I've Develop a retry mechanism by taking a reference from the following course. Below is the code I developed in Spring Batch, in this code @Recover method is not getting called. What am I doing wrong here ?

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

Below is the Controller

@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("===============");
}
}

答案1

得分: 1

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

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

如果你想使用基于注解的声明性方法,你需要在可重试的方法上添加 @Retryable 注解,并在恢复方法上添加 @Recover 注解。

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

英文:

You are using the retryTemplate in a programmatic way, so you need to provide the RecoveryCallback as a second parameter:

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

If you want to use the declarative approach using annotations, you need to annotate the retryable method with @Retryable and the recovery method with @Recover.

You can find an example of each approach in the home page: https://github.com/spring-projects/spring-retry#quick-start

huangapple
  • 本文由 发表于 2020年9月29日 16:14:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/64115536.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定