java - 当我们使用 RetryTemplate 时 Spring Retry 不起作用?
问题描述
我通过参考以下课程来开发重试机制。下面是我在 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
和用 .recovery 方法注解@Recover
。
您可以在主页中找到每种方法的示例:https ://github.com/spring-projects/spring-retry#quick-start
推荐阅读
- java - 使用 spring R2DBC 连接 mySQL 服务器版本 8 时出现未知系统变量“tx_isolation”
- r - 如何将一组观察结果与一个二元组匹配?
- javascript - 'parse' 的签名已被弃用
- azure - IoT 中心设备未接收到所有消息,即缺少一些云到设备 (C2D) 消息
- php - 跨服务器的无名列处理不一致
- postgresql - 字符串到 Postgresql json 数组
- sql - 使用“when”语句时如何选择多个列
- php - 使用谷歌自动完成和 laravel 自动完成地址
- sql - SQL 根据列的审计跟踪中的值返回 1 或 0
- nuxt.js - 如何将私有 API 密钥与 Nuxt(在客户端)一起使用?