java - Spring RetryTemplate 返回使用
问题描述
例如我有一个 Spring RetryTemplate 配置:
@Configuration
@EnableRetry
public class RetryTemplateConfig {
@Bean
public RetryTemplate retryTemplate() {
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(5);
FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
backOffPolicy.setBackOffPeriod(300000);
RetryTemplate template = new RetryTemplate();
template.setRetryPolicy(retryPolicy);
template.setBackOffPolicy(backOffPolicy);
return template;
}
}
如果捕获到异常,我想重新调用此方法:
@Scheduled(cron = "${schedule.cron.update}")
public void calculate() throws Exception {
log.info("Scheduled started");
try {
retryTemplate.execute(retryContext -> {
myService.work();
return true;
});
} catch (IOException | TemplateException e) {
log.error(e.toString());
}
log.info("Scheduled finished");
}
所以,我在服务类中的方法 work() 可以抛出异常:
public void send() throws IOException, TemplateException {
...
}
似乎它工作正常,但我真的不明白下一个代码是什么意思:
retryTemplate.execute(retryContext -> {
myService.work();
return true;
});
为什么我可以返回true
,null
和new Object()
其他东西?它会影响什么以及将在哪里使用?我应该返回什么?
解决方案
RetryTemplate 执行通用的RetryCallback,可以返回您定义的任何返回类型。
如果您需要从成功执行中获取数据,您可以在回调中返回它并稍后在流程中获取它
返回:操作成功的结果。
return template.execute(context -> { FileUtils.copyURLToFile(new URL(path), copy); return FileUtils.readFileToString(copy, Charset.defaultCharset());
推荐阅读
- selenium-webdriver - 尝试输入文本字段值时出现 Serenity 错误“分离事件”
- sql-server - 请求的 OLE DB 提供程序 Microsoft.ACE.OLEDB.12.0 未注册(SSIS 从 Access 源填充 SQL 表)
- sql - 有没有办法从文件系统备份中恢复 oracle 数据库
- xamarin - Xamarin Shell 中未设置活动 Shell 项
- javascript - TS2403:后续变量声明必须在反应中具有相同的类型
- java - 如何以编程方式在 Liferay DXP 中的每个类别下创建子类别?
- python - reportLab 使用大量内存生成大型 PDF 文件
- css - Django,强制重新加载 css/js,并收集静态
- android - 未收到 SkuDetails 列表
- r - 有没有办法从 1 个 excel 文件在 ArcGIS 中执行批量插值?