首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >@Retryable注释不适用于非Spring类方法

@Retryable注释不适用于非Spring类方法
EN

Stack Overflow用户
提问于 2021-11-23 10:41:29
回答 1查看 1.2K关注 0票数 1

我是spring-retry的新手。基本上,为了重新尝试REST调用,我已经将spring-retry集成到了我的spring应用程序中。为此,我作了以下修改:

  1. spring-retry添加到pom.xml中。
  2. 增加了以下配置: @Configuration @EnableRetry公共类RetryConfiguration {}
  3. 最后,将@Retryable注释添加到类(该类不是Spring )方法中,我希望对各种异常进行重试,如下所示: 公共类OAuth1RestClient扩展了OAuthRestClient {@重写@Retryable(maxAttempts = 3,maxAttempts={ Exception.class},退避=@退避(延迟= 100,乘子= 3)),公共响应executeRequest(OAuthRequest请求)抛出InterruptedException,ExecutionException,IOException { System.out.println("Inside Oauth1 client");返回myService.execute(请求);}

现在,executeRequest方法没有重新尝试。如果我在这里遗漏了什么,我就无法理解。

有人能帮忙吗?谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-23 10:59:33

如果您的类不是Spring管理的(例如@Component/@Bean),那么@Retryable的注释处理程序就不会将它捡起来。

您可以手动定义retryTemplate并使用它包装调用:

代码语言:javascript
复制
RetryTemplate.builder()
        .maxAttempts(2)
        .exponentialBackoff(100, 10, 1000)
        .retryOn(RestClientException.class)
        .traversingCauses()
        .build();

然后

代码语言:javascript
复制
retryTemplate.execute(context -> myService.execute(request));

如果要对多个异常重试,则可以通过自定义RetryPolicy进行重试。

代码语言:javascript
复制
Map<Class(? extends Throwable), Boolean> exceptionsMap = new HashMap<>();
exceptionsMap.put(InternalServerError.class, true);
exceptionsMap.put(RestClientException.class, true);

SimpleRetryPolicy policy = new SimpleRetryPolicy(5, exceptionsMap, true); 
RetryTemplate.builder()
        .customPolicy(policy)
        .exponentialBackoff(100, 10, 1000)
        .build();

FYI:RetryTemplate正在阻塞,您可能想探索一种非阻塞异步重试方法,比如异步重试。-并且retryOn()支持一个异常列表。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70079418

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档