Spring boot 重试框架 spring-retry 轻松解决 http 重试

青苗 青苗 | 722 | 2023-05-11

本文介绍是 API 业务重试,如果是 spring Cloud 分布式重试可以使用框架 https://github.com/aizuda/easy-retry

引入依赖

https://search.maven.org/artifact/org.springframework.retry/spring-retry

<dependency>
  <groupId>org.springframework.retry</groupId>
  <artifactId>spring-retry</artifactId>
  <version>2.0.1</version>
</dependency>

注解 @EnableRetry 启动

@EnableRetry
@SpringBootApplication
public class AzdApplication {
   ... 
}

@Retryable

@Retryable(value = RestClientException.class, backoff = @Backoff(delay = 5000L, multiplier = 2))
public String getRequest() throws Exception {
      ResponseEntity<String> responseEntity = restTemplate.getForEntity(address, String.class);
   // 获取响应结果
   return responseEntity.getBody();
}

@Retryable注解的方法在发生异常时会重试,参数说明:

  • value:当指定异常发生时会进行重试 ,HttpClientErrorException是RestClientException的子类。
  • include:和value一样,默认空。如果 exclude也为空时,所有异常都重试
  • exclude:指定异常不重试,默认空。如果 include也为空时,所有异常都重试
  • maxAttemps:最大重试次数,默认3
  • backoff:重试等待策略,默认空

@Backoff注解为重试等待的策略,参数说明:

  • delay:指定重试的延时时间,默认为1000毫秒
  • multiplier:指定延迟的倍数,比如设置delay=5000,multiplier=2时,第一次重试为5秒后,第二次为10(5x2)秒,第三次为20(10x2)秒。
文章标签: SpringBoot
推荐指数:

真诚点赞 诚不我欺~

Spring boot 重试框架 spring-retry 轻松解决 http 重试

点赞 收藏 评论