本文介紹了當我們使用RetryTemplate時,Spring重試不起作用嗎?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我通過引用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
這篇關于當我們使用RetryTemplate時,Spring重試不起作用嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,