精讲RestTemplate第8篇-请求失败自动重试机制

本文是精讲RestTemplate第8篇,前篇的blog访问地址以下:html

在上一节咱们为你们介绍了,当RestTemplate发起远程请求异常时的自定义处理方法,咱们能够经过自定义的方式解析出HTTP Status Code状态码,而后根据状态码和业务需求决定程序下一步该如何处理。
本节为你们介绍另一种通用的异常的处理机制:那就是自动重试。也就是说,在RestTemplate发送请求获得非200状态结果的时候,间隔必定的时间再次发送n次请求。n次请求都失败以后,最后抛出HttpClientErrorException。
在开始本节代码以前,将上一节的RestTemplate自定义异常处理的代码注释掉,不然自动重试机制不会生效。以下(参考上一节代码):vue

//restTemplate.setErrorHandler(new MyRestErrorHandler());

1、Spring Retry配置生效

经过maven坐标引入spring-retry,spring-retry的实现依赖于面向切面编程,因此引入aspectjweaver。如下配置过程都是基于Spring Boot应用。java

<dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
    <version>1.2.5.RELEASE</version>
</dependency>
<dependency>
   <groupId>org.aspectj</groupId>
   <artifactId>aspectjweaver</artifactId>
</dependency>

在Spring Boot 应用入口启动类,也就是配置类的上面加上@SpringRetry注解,表示让重试机制生效。spring

2、使用案例

@Service
public class RetryService {


  @Resource
  private RestTemplate restTemplate;

  private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


  @Retryable(value = RestClientException.class, maxAttempts = 3,
          backoff = @Backoff(delay = 5000L,multiplier = 2))
  public HttpStatus testEntity() {
    System.out.println("发起远程API请求:" + DATE_TIME_FORMATTER.format(LocalDateTime.now()));
    
    String url = "http://jsonplaceholder.typicode.com/postss/1";
    ResponseEntity<String> responseEntity
            = restTemplate.getForEntity(url, String.class);

    return responseEntity.getStatusCode(); // 获取响应码
  }


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

    • value:当指定异常发生时会进行重试 ,HttpClientErrorException是RestClientException的子类。
    • include:和value同样,默认空。若是 exclude也为空时,全部异常都重试 
    • exclude:指定异常不重试,默认空。若是 include也为空时,全部异常都重试 
    • maxAttemps:最大重试次数,默认3 
    • backoff:重试等待策略,默认空
  • @Backoff注解为重试等待的策略,参数说明:json

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

写一个测试的RetryController 对RetryService 的testEntity方法进行调用后端

@RestController
public class RetryController {
 
    @Resource
    private RetryService retryService;
 
    @GetMapping("/retry")
    public HttpStatus test() {
        return retryService.testEntity();
    }
}

3、测试结果

http://localhost:8080/retry 发起请求,结果以下:springboot

从结果能够看出:app

  • 第一次请求失败以后,延迟5秒后重试
  • 第二次请求失败以后,延迟10秒后重试
  • 第三次请求失败以后,抛出异常

欢迎关注个人博客,里面有不少精品合集

  • 本文转载注明出处(必须带链接,不能只转文字):字母哥博客

以为对您有帮助的话,帮我点赞、分享!您的支持是我不竭的创做动力! 。另外,笔者最近一段时间输出了以下的精品内容,期待您的关注。前后端分离

相关文章
相关标签/搜索