首页 > 解决方案 > 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,nullnew Object()其他东西?它会影响什么以及将在哪里使用?我应该返回什么?

标签: javaspringspring-retryretrytemplate

解决方案


RetryTemplate 执行通用的RetryCallback,可以返回您定义的任何返回类型。

如果您需要从成功执行中获取数据,您可以在回调中返回它并稍后在流程中获取它

返回:操作成功的结果。

重试读取文件示例

  return template.execute(context -> {
      FileUtils.copyURLToFile(new URL(path), copy);
      return FileUtils.readFileToString(copy, Charset.defaultCharset());

推荐阅读