前言
本文是精讲RestTemplate第8篇,前篇的blog访问地址如下:
RestTemplate在Spring或非Spring环境下使用精讲
RestTemplate实现多种底层HTTP客户端类库的切换用法
RestTemplate发送HTTP GET请求使用方法详解
RestTemplate发送HTTP POST请求使用方法详解
在上一节我们为大家介绍了,当RestTemplate发起远程请求异常时的自定义处理方法,我们可以通过自定义的方式解析出HTTP Status Code状态码,然后根据状态码和业务需求决定程序下一步该如何处理。 本节为大家介绍另外一种通用的异常的处理机制:那就是自动重试。也就是说,在RestTemplate发送请求得到非200状态结果的时候,间隔一定的时间再次发送n次请求。n次请求都失败之后,最后抛出HttpClientErrorException。 在开始本节代码之前,将上一节的RestTemplate自定义异常处理的代码注释掉,否则自动重试机制不会生效。如下(参考上一节代码):
1
|
//restTemplate.setErrorHandler(new MyRestErrorHandler()); |
一、Spring Retry配置生效
通过maven坐标引入spring-retry,spring-retry的实现依赖于面向切面编程,所以引入aspectjweaver。以下配置过程都是基于Spring Boot应用。
1
2
3
4
5
6
7
8
9
|
< 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注解,表示让重试机制生效。
二、使用案例
写一个模拟的业务类RetryService ,在其里面注入RestTemplate 。
RestTemplate 实例化Bean配置参考:
RestTemplate在Spring或非Spring环境下使用精讲
RestTemplate实现多种底层HTTP客户端类库的切换用法进行实现。
将正确的请求服务地址由“/posts/1”改成“/postss/1”。服务不存在所以抛出404异常,是为了触发重试机制。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
@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
注解为重试等待的策略,参数说明:
delay
:指定重试的延时时间,默认为1000毫秒
multiplier
:指定延迟的倍数,比如设置delay=5000,multiplier=2时,第一次重试为5秒后,第二次为10(5x2)秒,第三次为20(10x2)秒。
写一个测试的RetryController 对RetryService 的testEntity方法进行调用
1
2
3
4
5
6
7
8
9
|
@RestController public class RetryController { @Resource private RetryService retryService; @GetMapping ( "/retry" ) public HttpStatus test() { return retryService.testEntity(); } } |
三、测试结果
向 http://localhost:8080/retry 发起请求,结果如下:
从结果可以看出:
第一次请求失败之后,延迟5秒后重试
第二次请求失败之后,延迟10秒后重试
第三次请求失败之后,抛出异常
以上就是RestTemplate请求失败自动重启机制精讲的详细内容,更多关于RestTemplate请求失败自动重启的资料请关注服务器之家其它相关文章!
原文链接:https://zimug.blog.csdn.net/article/details/108019319