【问题标题】:Spring RetryTemplate return usageSpring RetryTemplate 返回使用
【发布时间】:2020-10-12 08:13:02
【问题描述】:

例如我有一个 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;
            });

为什么我可以返回truenullnew Object() 和其他东西?它会影响什么以及将在哪里使用?我应该返回什么?

【问题讨论】:

    标签: java spring spring-retry retrytemplate


    【解决方案1】:

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

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

    返回: 操作成功的结果。

    Example 重试读取文件:

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

    【讨论】:

    • 顺便说一句,我应该抓住Exception 抛出的execute 方法吗?
    • @hsadik 通常你希望抛出异常来触发重试机制
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    相关资源
    最近更新 更多